From ac29b7c719a7d07e2f3a761fca8564edf3cb3633 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 12 Jan 2018 12:36:53 -0600 Subject: [PATCH 001/212] Make cross section arrays in sum_xs contiguous --- src/cross_section.F90 | 24 ++++++++--------- src/nuclide_header.F90 | 60 +++++++++++++++++++++--------------------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index 69e5779669..f0d81f8928 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -266,29 +266,29 @@ contains micro_xs(i_nuclide) % interp_factor = f ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % total = (ONE - f) * xs % total(i_grid) & - + f * xs % total(i_grid + 1) + micro_xs(i_nuclide) % total = (ONE - f) * xs % value(SUM_XS_TOTAL,i_grid) & + + f * xs % value(SUM_XS_TOTAL,i_grid + 1) ! Calculate microscopic nuclide elastic cross section - micro_xs(i_nuclide) % elastic = (ONE - f) * xs % elastic(i_grid) & - + f * xs % elastic(i_grid + 1) - - ! Calculate microscopic nuclide absorption cross section - micro_xs(i_nuclide) % absorption = (ONE - f) * xs % absorption( & - i_grid) + f * xs % absorption(i_grid + 1) + micro_xs(i_nuclide) % elastic = (ONE - f) * xs % value(SUM_XS_ELASTIC,i_grid) & + + f * xs % value(SUM_XS_ELASTIC,i_grid + 1) if (nuc % fissionable) then ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % fission = (ONE - f) * xs % fission(i_grid) & - + f * xs % fission(i_grid + 1) + micro_xs(i_nuclide) % fission = (ONE - f) * xs % value(SUM_XS_FISSION,i_grid) & + + f * xs % value(SUM_XS_FISSION,i_grid + 1) ! Calculate microscopic nuclide nu-fission cross section - micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % nu_fission( & - i_grid) + f * xs % nu_fission(i_grid + 1) + micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % value(SUM_XS_NU_FISSION, & + i_grid) + f * xs % value(SUM_XS_NU_FISSION,i_grid + 1) else micro_xs(i_nuclide) % fission = ZERO micro_xs(i_nuclide) % nu_fission = ZERO end if + + ! Calculate microscopic nuclide absorption cross section + micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(SUM_XS_ABSORPTION, & + i_grid) + f * xs % value(SUM_XS_ABSORPTION,i_grid + 1) end associate ! Depletion-related reactions diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 38e89b6483..e204f68de1 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -36,13 +36,22 @@ module nuclide_header real(8), allocatable :: energy(:) ! energy values corresponding to xs end type EnergyGrid + integer, parameter :: & + SUM_XS_TOTAL = 1, & + SUM_XS_ELASTIC = 2, & + SUM_XS_FISSION = 3, & + SUM_XS_NU_FISSION = 4, & + SUM_XS_ABSORPTION = 5, & + SUM_XS_HEATING = 6 + type SumXS - real(8), allocatable :: total(:) ! total cross section - real(8), allocatable :: elastic(:) ! elastic scattering - real(8), allocatable :: fission(:) ! fission - real(8), allocatable :: nu_fission(:) ! neutron production - real(8), allocatable :: absorption(:) ! absorption (MT > 100) - real(8), allocatable :: heating(:) ! heating + real(8), allocatable :: value(:,:) +!!$ real(8), allocatable :: total(:) ! total cross section +!!$ real(8), allocatable :: elastic(:) ! elastic scattering +!!$ real(8), allocatable :: fission(:) ! fission +!!$ real(8), allocatable :: nu_fission(:) ! neutron production +!!$ real(8), allocatable :: absorption(:) ! absorption (MT > 100) +!!$ real(8), allocatable :: heating(:) ! heating end type SumXS type :: Nuclide @@ -571,16 +580,8 @@ contains do i = 1, n_temperature ! Allocate and initialize derived cross sections n_grid = size(this % grid(i) % energy) - allocate(this % sum_xs(i) % total(n_grid)) - allocate(this % sum_xs(i) % elastic(n_grid)) - allocate(this % sum_xs(i) % fission(n_grid)) - allocate(this % sum_xs(i) % nu_fission(n_grid)) - allocate(this % sum_xs(i) % absorption(n_grid)) - this % sum_xs(i) % total(:) = ZERO - this % sum_xs(i) % elastic(:) = ZERO - this % sum_xs(i) % fission(:) = ZERO - this % sum_xs(i) % nu_fission(:) = ZERO - this % sum_xs(i) % absorption(:) = ZERO + allocate(this % sum_xs(i) % value(6,n_grid)) + this % sum_xs(i) % value(:,:) = ZERO end do i_fission = 0 @@ -608,16 +609,17 @@ contains n = size(rx % xs(t) % value) ! Copy elastic - if (rx % MT == ELASTIC) this % sum_xs(t) % elastic(:) = rx % xs(t) % value + if (rx % MT == ELASTIC) this % sum_xs(t) % value(SUM_XS_ELASTIC,:) = & + rx % xs(t) % value ! Add contribution to total cross section - this % sum_xs(t) % total(j:j+n-1) = this % sum_xs(t) % total(j:j+n-1) + & - rx % xs(t) % value + this % sum_xs(t) % value(SUM_XS_TOTAL,j:j+n-1) = this % sum_xs(t) % & + value(SUM_XS_TOTAL,j:j+n-1) + rx % xs(t) % value ! Add contribution to absorption cross section if (is_disappearance(rx % MT)) then - this % sum_xs(t) % absorption(j:j+n-1) = this % sum_xs(t) % & - absorption(j:j+n-1) + rx % xs(t) % value + this % sum_xs(t) % value(SUM_XS_ABSORPTION,j:j+n-1) = this % sum_xs(t) % & + value(SUM_XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value end if ! Information about fission reactions @@ -633,12 +635,12 @@ contains ! Add contribution to fission cross section if (is_fission(rx % MT)) then this % fissionable = .true. - this % sum_xs(t) % fission(j:j+n-1) = this % sum_xs(t) % & - fission(j:j+n-1) + rx % xs(t) % value + this % sum_xs(t) % value(SUM_XS_FISSION,j:j+n-1) = this % sum_xs(t) % & + value(SUM_XS_FISSION,j:j+n-1) + rx % xs(t) % value ! Also need to add fission cross sections to absorption - this % sum_xs(t) % absorption(j:j+n-1) = this % sum_xs(t) % & - absorption(j:j+n-1) + rx % xs(t) % value + this % sum_xs(t) % value(SUM_XS_ABSORPTION,j:j+n-1) = this % sum_xs(t) % & + value(SUM_XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value ! If total fission reaction is present, there's no need to store the ! reaction cross-section since it was copied to this % fission @@ -689,12 +691,10 @@ contains ! Calculate nu-fission cross section do t = 1, n_temperature if (this % fissionable) then - do i = 1, size(this % sum_xs(t) % fission) - this % sum_xs(t) % nu_fission(i) = this % nu(this % grid(t) % energy(i), & - EMISSION_TOTAL) * this % sum_xs(t) % fission(i) + do i = 1, n_grid + this % sum_xs(t) % value(SUM_XS_NU_FISSION,i) = this % nu(this % grid(t) % energy(i), & + EMISSION_TOTAL) * this % sum_xs(t) % value(SUM_XS_FISSION,i) end do - else - this % sum_xs(t) % nu_fission(:) = ZERO end if end do end subroutine nuclide_create_derived From d2d1703e7671285efb855af929d9ff57cb293131 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 12 Jan 2018 15:06:04 -0600 Subject: [PATCH 002/212] Aesthetic changes. Rename sum_xs, rename SUM_XS -> XS constants --- src/cross_section.F90 | 22 +++++++++--------- src/nuclide_header.F90 | 53 +++++++++++++++++++++--------------------- 2 files changed, 37 insertions(+), 38 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index f0d81f8928..1dfa7f52b7 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -233,7 +233,7 @@ contains if (f > prn()) i_temp = i_temp + 1 end select - associate (grid => nuc % grid(i_temp), xs => nuc % sum_xs(i_temp)) + associate (grid => nuc % grid(i_temp), xs => nuc % xs(i_temp)) ! Determine the energy grid index using a logarithmic mapping to ! reduce the energy range over which a binary search needs to be ! performed @@ -266,29 +266,29 @@ contains micro_xs(i_nuclide) % interp_factor = f ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % total = (ONE - f) * xs % value(SUM_XS_TOTAL,i_grid) & - + f * xs % value(SUM_XS_TOTAL,i_grid + 1) + micro_xs(i_nuclide) % total = (ONE - f) * xs % value(XS_TOTAL,i_grid) & + + f * xs % value(XS_TOTAL,i_grid + 1) ! Calculate microscopic nuclide elastic cross section - micro_xs(i_nuclide) % elastic = (ONE - f) * xs % value(SUM_XS_ELASTIC,i_grid) & - + f * xs % value(SUM_XS_ELASTIC,i_grid + 1) + micro_xs(i_nuclide) % elastic = (ONE - f) * xs % value(XS_ELASTIC,i_grid) & + + f * xs % value(XS_ELASTIC,i_grid + 1) if (nuc % fissionable) then ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % fission = (ONE - f) * xs % value(SUM_XS_FISSION,i_grid) & - + f * xs % value(SUM_XS_FISSION,i_grid + 1) + micro_xs(i_nuclide) % fission = (ONE - f) * xs % value(XS_FISSION,i_grid) & + + f * xs % value(XS_FISSION,i_grid + 1) ! Calculate microscopic nuclide nu-fission cross section - micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % value(SUM_XS_NU_FISSION, & - i_grid) + f * xs % value(SUM_XS_NU_FISSION,i_grid + 1) + micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % value(XS_NU_FISSION, & + i_grid) + f * xs % value(XS_NU_FISSION,i_grid + 1) else micro_xs(i_nuclide) % fission = ZERO micro_xs(i_nuclide) % nu_fission = ZERO end if ! Calculate microscopic nuclide absorption cross section - micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(SUM_XS_ABSORPTION, & - i_grid) + f * xs % value(SUM_XS_ABSORPTION,i_grid + 1) + micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & + i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) end associate ! Depletion-related reactions diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index e204f68de1..88e9348562 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -36,22 +36,20 @@ module nuclide_header real(8), allocatable :: energy(:) ! energy values corresponding to xs end type EnergyGrid + ! Positions for first dimension of Nuclide % xs integer, parameter :: & - SUM_XS_TOTAL = 1, & - SUM_XS_ELASTIC = 2, & - SUM_XS_FISSION = 3, & - SUM_XS_NU_FISSION = 4, & - SUM_XS_ABSORPTION = 5, & - SUM_XS_HEATING = 6 + XS_TOTAL = 1, & + XS_ELASTIC = 2, & + XS_FISSION = 3, & + XS_NU_FISSION = 4, & + XS_ABSORPTION = 5, & + XS_HEATING = 6 + ! The array within SumXS is of shape (6, n_energy) where the first dimension + ! corresponds to the following values: 1) total, 2) elastic scattering, 3) + ! fission, 4) neutron production, 5) absorption (MT > 100), 6) heating type SumXS real(8), allocatable :: value(:,:) -!!$ real(8), allocatable :: total(:) ! total cross section -!!$ real(8), allocatable :: elastic(:) ! elastic scattering -!!$ real(8), allocatable :: fission(:) ! fission -!!$ real(8), allocatable :: nu_fission(:) ! neutron production -!!$ real(8), allocatable :: absorption(:) ! absorption (MT > 100) -!!$ real(8), allocatable :: heating(:) ! heating end type SumXS type :: Nuclide @@ -70,7 +68,7 @@ module nuclide_header type(EnergyGrid), allocatable :: grid(:) ! Microscopic cross sections - type(SumXS), allocatable :: sum_xs(:) + type(SumXS), allocatable :: xs(:) ! Resonance scattering info logical :: resonant = .false. ! resonant scatterer? @@ -575,13 +573,13 @@ contains type(VectorInt) :: MTs n_temperature = size(this % kTs) - allocate(this % sum_xs(n_temperature)) + allocate(this % xs(n_temperature)) this % reaction_index(:) = 0 do i = 1, n_temperature ! Allocate and initialize derived cross sections n_grid = size(this % grid(i) % energy) - allocate(this % sum_xs(i) % value(6,n_grid)) - this % sum_xs(i) % value(:,:) = ZERO + allocate(this % xs(i) % value(6,n_grid)) + this % xs(i) % value(:,:) = ZERO end do i_fission = 0 @@ -609,17 +607,17 @@ contains n = size(rx % xs(t) % value) ! Copy elastic - if (rx % MT == ELASTIC) this % sum_xs(t) % value(SUM_XS_ELASTIC,:) = & + if (rx % MT == ELASTIC) this % xs(t) % value(XS_ELASTIC,:) = & rx % xs(t) % value ! Add contribution to total cross section - this % sum_xs(t) % value(SUM_XS_TOTAL,j:j+n-1) = this % sum_xs(t) % & - value(SUM_XS_TOTAL,j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_TOTAL,j:j+n-1) = this % xs(t) % & + value(XS_TOTAL,j:j+n-1) + rx % xs(t) % value ! Add contribution to absorption cross section if (is_disappearance(rx % MT)) then - this % sum_xs(t) % value(SUM_XS_ABSORPTION,j:j+n-1) = this % sum_xs(t) % & - value(SUM_XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_ABSORPTION,j:j+n-1) = this % xs(t) % & + value(XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value end if ! Information about fission reactions @@ -635,12 +633,12 @@ contains ! Add contribution to fission cross section if (is_fission(rx % MT)) then this % fissionable = .true. - this % sum_xs(t) % value(SUM_XS_FISSION,j:j+n-1) = this % sum_xs(t) % & - value(SUM_XS_FISSION,j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_FISSION,j:j+n-1) = this % xs(t) % & + value(XS_FISSION,j:j+n-1) + rx % xs(t) % value ! Also need to add fission cross sections to absorption - this % sum_xs(t) % value(SUM_XS_ABSORPTION,j:j+n-1) = this % sum_xs(t) % & - value(SUM_XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value + this % xs(t) % value(XS_ABSORPTION,j:j+n-1) = this % xs(t) % & + value(XS_ABSORPTION,j:j+n-1) + rx % xs(t) % value ! If total fission reaction is present, there's no need to store the ! reaction cross-section since it was copied to this % fission @@ -692,8 +690,9 @@ contains do t = 1, n_temperature if (this % fissionable) then do i = 1, n_grid - this % sum_xs(t) % value(SUM_XS_NU_FISSION,i) = this % nu(this % grid(t) % energy(i), & - EMISSION_TOTAL) * this % sum_xs(t) % value(SUM_XS_FISSION,i) + this % xs(t) % value(XS_NU_FISSION,i) = & + this % nu(this % grid(t) % energy(i), EMISSION_TOTAL) * & + this % xs(t) % value(XS_FISSION,i) end do end if end do From df40af793b94db0580ca42567403e1562a8bb909 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 12 Jan 2018 15:09:09 -0600 Subject: [PATCH 003/212] Minor simplification on multipole branch in calculate_nuclide_xs --- src/cross_section.F90 | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index 1dfa7f52b7..0a944f2118 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -181,14 +181,13 @@ contains call multipole_eval(nuc % multipole, E, sqrtkT, sig_t, sig_a, sig_f) micro_xs(i_nuclide) % total = sig_t - micro_xs(i_nuclide) % absorption = sig_a micro_xs(i_nuclide) % elastic = sig_t - sig_a + micro_xs(i_nuclide) % absorption = sig_a + micro_xs(i_nuclide) % fission = sig_f if (nuc % fissionable) then - micro_xs(i_nuclide) % fission = sig_f micro_xs(i_nuclide) % nu_fission = sig_f * nuc % nu(E, EMISSION_TOTAL) else - micro_xs(i_nuclide) % fission = ZERO micro_xs(i_nuclide) % nu_fission = ZERO end if From 21585e937cbcae426324f497ce8492155807104a Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 12 Jan 2018 15:44:30 -0600 Subject: [PATCH 004/212] Remove elastic from sum_xs and caches --- src/cross_section.F90 | 29 ++++++++++++++++------------- src/nuclide_header.F90 | 16 +++++----------- src/physics.F90 | 12 ++++++++++++ src/tallies/tally.F90 | 14 -------------- 4 files changed, 33 insertions(+), 38 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index 0a944f2118..82e3c00e8b 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -42,7 +42,6 @@ contains ! Set all material macroscopic cross sections to zero material_xs % total = ZERO - material_xs % elastic = ZERO material_xs % absorption = ZERO material_xs % fission = ZERO material_xs % nu_fission = ZERO @@ -115,10 +114,6 @@ contains material_xs % total = material_xs % total + & atom_density * micro_xs(i_nuclide) % total - ! Add contributions to material macroscopic scattering cross section - material_xs % elastic = material_xs % elastic + & - atom_density * micro_xs(i_nuclide) % elastic - ! Add contributions to material macroscopic absorption cross section material_xs % absorption = material_xs % absorption + & atom_density * micro_xs(i_nuclide) % absorption @@ -162,6 +157,7 @@ contains real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables ! Initialize cached cross sections to zero + micro_xs(i_nuclide) % elastic = ZERO micro_xs(i_nuclide) % thermal = ZERO micro_xs(i_nuclide) % thermal_elastic = ZERO @@ -181,7 +177,6 @@ contains call multipole_eval(nuc % multipole, E, sqrtkT, sig_t, sig_a, sig_f) micro_xs(i_nuclide) % total = sig_t - micro_xs(i_nuclide) % elastic = sig_t - sig_a micro_xs(i_nuclide) % absorption = sig_a micro_xs(i_nuclide) % fission = sig_f @@ -268,9 +263,9 @@ contains micro_xs(i_nuclide) % total = (ONE - f) * xs % value(XS_TOTAL,i_grid) & + f * xs % value(XS_TOTAL,i_grid + 1) - ! Calculate microscopic nuclide elastic cross section - micro_xs(i_nuclide) % elastic = (ONE - f) * xs % value(XS_ELASTIC,i_grid) & - + f * xs % value(XS_ELASTIC,i_grid + 1) + ! Calculate microscopic nuclide absorption cross section + micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & + i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) if (nuc % fissionable) then ! Calculate microscopic nuclide total cross section @@ -284,10 +279,6 @@ contains micro_xs(i_nuclide) % fission = ZERO micro_xs(i_nuclide) % nu_fission = ZERO end if - - ! Calculate microscopic nuclide absorption cross section - micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & - i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) end associate ! Depletion-related reactions @@ -450,6 +441,18 @@ contains micro_xs(i_nuclide) % thermal = sab_frac * (elastic + inelastic) micro_xs(i_nuclide) % thermal_elastic = sab_frac * elastic + ! Calculate free atom elastic cross section + f = micro_xs(i_nuclide) % interp_factor + i_grid = micro_xs(i_nuclide) % index_grid + i_temp = micro_xs(i_nuclide) % index_temp + if (i_temp > 0) then + associate (xs => nuclides(i_nuclide) % reactions(1) % xs(i_temp) % value) + micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) + end associate + else + micro_xs(i_nuclide) % elastic = ZERO + end if + ! Correct total and elastic cross sections micro_xs(i_nuclide) % total = micro_xs(i_nuclide) % total & + micro_xs(i_nuclide) % thermal & diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 88e9348562..23e6e5825f 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -39,11 +39,9 @@ module nuclide_header ! Positions for first dimension of Nuclide % xs integer, parameter :: & XS_TOTAL = 1, & - XS_ELASTIC = 2, & + XS_ABSORPTION = 2, & XS_FISSION = 3, & - XS_NU_FISSION = 4, & - XS_ABSORPTION = 5, & - XS_HEATING = 6 + XS_NU_FISSION = 4 ! The array within SumXS is of shape (6, n_energy) where the first dimension ! corresponds to the following values: 1) total, 2) elastic scattering, 3) @@ -120,11 +118,12 @@ module nuclide_header type NuclideMicroXS ! Microscopic cross sections in barns real(8) :: total - real(8) :: elastic ! If sab_frac is not 1 or 0, then this value is - ! averaged over bound and non-bound nuclei real(8) :: absorption ! absorption (disappearance) real(8) :: fission ! fission real(8) :: nu_fission ! neutron production from fission + + real(8) :: elastic ! If sab_frac is not 1 or 0, then this value is + ! averaged over bound and non-bound nuclei real(8) :: thermal ! Bound thermal elastic & inelastic scattering real(8) :: thermal_elastic ! Bound thermal elastic scattering @@ -155,7 +154,6 @@ module nuclide_header type MaterialMacroXS real(8) :: total ! macroscopic total xs - real(8) :: elastic ! macroscopic elastic scattering xs real(8) :: absorption ! macroscopic absorption xs real(8) :: fission ! macroscopic fission xs real(8) :: nu_fission ! macroscopic production xs @@ -606,10 +604,6 @@ contains j = rx % xs(t) % threshold n = size(rx % xs(t) % value) - ! Copy elastic - if (rx % MT == ELASTIC) this % xs(t) % value(XS_ELASTIC,:) = & - rx % xs(t) % value - ! Add contribution to total cross section this % xs(t) % value(XS_TOTAL,j:j+n-1) = this % xs(t) % & value(XS_TOTAL,j:j+n-1) + rx % xs(t) % value diff --git a/src/physics.F90 b/src/physics.F90 index d13313e05a..5d31d87d7b 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -338,6 +338,18 @@ contains micro_xs(i_nuclide) % absorption) sampled = .false. + ! Calculate elastic cross section if need be + if (micro_xs(i_nuclide) % elastic == ZERO) then + if (i_temp > 0) then + associate (xs => nuc % reactions(1) % xs(i_temp) % value) + micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) + end associate + else + micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % total - & + micro_xs(i_nuclide) % absorption + end if + end if + prob = micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % thermal if (prob > cutoff) then ! ======================================================================= diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index 7684a36aa6..d3dbf888d1 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -1009,20 +1009,6 @@ contains ! Simply count number of scoring events score = ONE - case (ELASTIC) - if (t % estimator == ESTIMATOR_ANALOG) then - ! Check if event MT matches - if (p % event_MT /= ELASTIC) cycle SCORE_LOOP - score = p % last_wgt * flux - - else - if (i_nuclide > 0) then - score = micro_xs(i_nuclide) % elastic * atom_density * flux - else - score = material_xs % elastic * flux - end if - end if - case (SCORE_FISS_Q_PROMPT) score = ZERO From 0cf1f918f5386ffc77654b181ea5caecab713a82 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 15 Jan 2018 16:44:18 -0600 Subject: [PATCH 005/212] Put automatic arrays on stack when using gfortran (for multipole performance) --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c5150745b6..51bdcc4d9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,9 +116,9 @@ if(CMAKE_Fortran_COMPILER_ID STREQUAL GNU) endif() # GCC compiler options - list(APPEND f90flags -cpp -std=f2008ts -fbacktrace -O2) + list(APPEND f90flags -cpp -std=f2008ts -fbacktrace -O2 -fstack-arrays) if(debug) - list(REMOVE_ITEM f90flags -O2) + list(REMOVE_ITEM f90flags -O2 -fstack-arrays) list(APPEND f90flags -g -Wall -Wno-unused-dummy-argument -pedantic -fbounds-check -ffpe-trap=invalid,overflow,underflow) list(APPEND ldflags -g) From 7d7453b8ffbbfa4e8c82b152c9e00a5b644e29bd Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 15 Jan 2018 17:25:21 -0600 Subject: [PATCH 006/212] Make sure elastic scattering cross section is precalculated for use in URR --- src/cross_section.F90 | 44 +++++++++++++++++++++++++++++++----------- src/nuclide_header.F90 | 8 ++++---- src/physics.F90 | 15 ++++---------- 3 files changed, 41 insertions(+), 26 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index 82e3c00e8b..22598dc422 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -157,7 +157,7 @@ contains real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables ! Initialize cached cross sections to zero - micro_xs(i_nuclide) % elastic = ZERO + micro_xs(i_nuclide) % elastic = -ONE micro_xs(i_nuclide) % thermal = ZERO micro_xs(i_nuclide) % thermal_elastic = ZERO @@ -442,16 +442,7 @@ contains micro_xs(i_nuclide) % thermal_elastic = sab_frac * elastic ! Calculate free atom elastic cross section - f = micro_xs(i_nuclide) % interp_factor - i_grid = micro_xs(i_nuclide) % index_grid - i_temp = micro_xs(i_nuclide) % index_temp - if (i_temp > 0) then - associate (xs => nuclides(i_nuclide) % reactions(1) % xs(i_temp) % value) - micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) - end associate - else - micro_xs(i_nuclide) % elastic = ZERO - end if + call calculate_elastic_xs(i_nuclide) ! Correct total and elastic cross sections micro_xs(i_nuclide) % total = micro_xs(i_nuclide) % total & @@ -581,6 +572,7 @@ contains ! Multiply by smooth cross-section if needed if (urr % multiply_smooth) then + call calculate_elastic_xs(i_nuclide) elastic = elastic * micro_xs(i_nuclide) % elastic capture = capture * (micro_xs(i_nuclide) % absorption - & micro_xs(i_nuclide) % fission) @@ -609,6 +601,36 @@ contains end subroutine calculate_urr_xs +!=============================================================================== +! CALCULATE_ELASTIC_XS precalculates the free atom elastic scattering cross +! section. Normally it is not needed until a collision actually occurs in a +! material. However, in the thermal and unresolved resonance regions, we have to +! calculate it early to adjust the total cross section correctly. +!=============================================================================== + + subroutine calculate_elastic_xs(i_nuclide) + integer, intent(in) :: i_nuclide + + integer :: i_temp + integer :: i_grid + real(8) :: f + + ! Get temperature index, grid index, and interpolation factor + i_temp = micro_xs(i_nuclide) % index_temp + i_grid = micro_xs(i_nuclide) % index_grid + f = micro_xs(i_nuclide) % interp_factor + + if (i_temp > 0) then + associate (xs => nuclides(i_nuclide) % reactions(1) % xs(i_temp) % value) + micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) + end associate + else + ! For multipole, elastic is total - absorption + micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % total - & + micro_xs(i_nuclide) % absorption + end if + end subroutine calculate_elastic_xs + !=============================================================================== ! MULTIPOLE_EVAL evaluates the windowed multipole equations for cross ! sections in the resolved resonance regions diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 23e6e5825f..328fe123aa 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -43,9 +43,9 @@ module nuclide_header XS_FISSION = 3, & XS_NU_FISSION = 4 - ! The array within SumXS is of shape (6, n_energy) where the first dimension - ! corresponds to the following values: 1) total, 2) elastic scattering, 3) - ! fission, 4) neutron production, 5) absorption (MT > 100), 6) heating + ! The array within SumXS is of shape (4, n_energy) where the first dimension + ! corresponds to the following values: 1) total, 2) absorption (MT > 100), 3) + ! fission, 4) neutron production type SumXS real(8), allocatable :: value(:,:) end type SumXS @@ -576,7 +576,7 @@ contains do i = 1, n_temperature ! Allocate and initialize derived cross sections n_grid = size(this % grid(i) % energy) - allocate(this % xs(i) % value(6,n_grid)) + allocate(this % xs(i) % value(4,n_grid)) this % xs(i) % value(:,:) = ZERO end do diff --git a/src/physics.F90 b/src/physics.F90 index 5d31d87d7b..cb28778240 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -2,7 +2,7 @@ module physics use algorithm, only: binary_search use constants - use cross_section, only: elastic_xs_0K + use cross_section, only: elastic_xs_0K, calculate_elastic_xs use endf, only: reaction_name use error, only: fatal_error, warning, write_message use material_header, only: Material, materials @@ -338,16 +338,9 @@ contains micro_xs(i_nuclide) % absorption) sampled = .false. - ! Calculate elastic cross section if need be - if (micro_xs(i_nuclide) % elastic == ZERO) then - if (i_temp > 0) then - associate (xs => nuc % reactions(1) % xs(i_temp) % value) - micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) - end associate - else - micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % total - & - micro_xs(i_nuclide) % absorption - end if + ! Calculate elastic cross section if it wasn't precalculated + if (micro_xs(i_nuclide) % elastic < ZERO) then + call calculate_elastic_xs(i_nuclide) end if prob = micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % thermal From f74c2fae563ff944902059c0d786940723a9a885 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 15 Jan 2018 17:54:34 -0600 Subject: [PATCH 007/212] Fix elastic scattering rate tallies --- src/tallies/tally.F90 | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index d3dbf888d1..eb17070c11 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -4,7 +4,7 @@ module tally use algorithm, only: binary_search use constants - use cross_section, only: multipole_deriv_eval + use cross_section, only: multipole_deriv_eval, calculate_elastic_xs use dict_header, only: EMPTY use error, only: fatal_error use geometry_header @@ -1009,6 +1009,37 @@ contains ! Simply count number of scoring events score = ONE + case (ELASTIC) + if (t % estimator == ESTIMATOR_ANALOG) then + ! Check if event MT matches + if (p % event_MT /= ELASTIC) cycle SCORE_LOOP + score = p % last_wgt * flux + + else + if (i_nuclide > 0) then + if (micro_xs(i_nuclide) % elastic < ZERO) then + call calculate_elastic_xs(i_nuclide) + end if + score = micro_xs(i_nuclide) % elastic * atom_density * flux + else + score = ZERO + if (p % material /= MATERIAL_VOID) then + do l = 1, materials(p % material) % n_nuclides + ! Get atom density + atom_density_ = materials(p % material) % atom_density(l) + + ! Get index in nuclides array + i_nuc = materials(p % material) % nuclide(l) + if (micro_xs(i_nuc) % elastic < ZERO) then + call calculate_elastic_xs(i_nuc) + end if + + score = score + micro_xs(i_nuc) % elastic * atom_density_ * flux + end do + end if + end if + end if + case (SCORE_FISS_Q_PROMPT) score = ZERO From e300c84db5618d74fa636b0a61185a16245398b1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 17 Jan 2018 12:02:01 -0600 Subject: [PATCH 008/212] Replace -ONE with an arbitrary value in named constant CACHE_INVALID --- src/cross_section.F90 | 2 +- src/nuclide_header.F90 | 4 ++++ src/physics.F90 | 2 +- src/tallies/tally.F90 | 4 ++-- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/cross_section.F90 b/src/cross_section.F90 index 22598dc422..47e1c4fc5d 100644 --- a/src/cross_section.F90 +++ b/src/cross_section.F90 @@ -157,7 +157,7 @@ contains real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables ! Initialize cached cross sections to zero - micro_xs(i_nuclide) % elastic = -ONE + micro_xs(i_nuclide) % elastic = CACHE_INVALID micro_xs(i_nuclide) % thermal = ZERO micro_xs(i_nuclide) % thermal_elastic = ZERO diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 328fe123aa..1ca5849146 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -115,6 +115,10 @@ module nuclide_header ! nuclide at the current energy !=============================================================================== + ! Arbitrary value to indicate invalid cache state for elastic scattering + ! (NuclideMicroXS % elastic) + real(8), parameter :: CACHE_INVALID = dble(Z"FFE0000000000000") + type NuclideMicroXS ! Microscopic cross sections in barns real(8) :: total diff --git a/src/physics.F90 b/src/physics.F90 index cb28778240..fe242dbb78 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -339,7 +339,7 @@ contains sampled = .false. ! Calculate elastic cross section if it wasn't precalculated - if (micro_xs(i_nuclide) % elastic < ZERO) then + if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then call calculate_elastic_xs(i_nuclide) end if diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index eb17070c11..027e335e91 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -1017,7 +1017,7 @@ contains else if (i_nuclide > 0) then - if (micro_xs(i_nuclide) % elastic < ZERO) then + if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then call calculate_elastic_xs(i_nuclide) end if score = micro_xs(i_nuclide) % elastic * atom_density * flux @@ -1030,7 +1030,7 @@ contains ! Get index in nuclides array i_nuc = materials(p % material) % nuclide(l) - if (micro_xs(i_nuc) % elastic < ZERO) then + if (micro_xs(i_nuc) % elastic == CACHE_INVALID) then call calculate_elastic_xs(i_nuc) end if From 2821ce589f6dc81b40c593e2a20e0f6165dddde4 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Thu, 18 Jan 2018 18:04:15 -0500 Subject: [PATCH 009/212] Add to rng and rnc --- src/relaxng/settings.rnc | 2 ++ src/relaxng/settings.rng | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/src/relaxng/settings.rnc b/src/relaxng/settings.rnc index 19a2948c58..282c685db1 100644 --- a/src/relaxng/settings.rnc +++ b/src/relaxng/settings.rnc @@ -3,6 +3,8 @@ element settings { element confidence_intervals { xsd:boolean }? & + element create_fission_neutrons { xsd:boolean }? & + element cutoff { (element weight { xsd:double } | attribute weight { xsd:double })? & (element weight_avg { xsd:double } | attribute weight_avg { xsd:double })? diff --git a/src/relaxng/settings.rng b/src/relaxng/settings.rng index 606b978290..0018cb16bd 100644 --- a/src/relaxng/settings.rng +++ b/src/relaxng/settings.rng @@ -11,6 +11,11 @@ + + + + + From 91ccc4da0051a3d1f75286bbc4c2305cd720867f Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 8 Aug 2017 18:10:53 -0400 Subject: [PATCH 010/212] Implement z planes and cylinders in C++ --- CMakeLists.txt | 5 +- src/geometry.F90 | 47 +++++++- src/input_xml.F90 | 9 ++ src/surface_header.C | 280 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 src/surface_header.C diff --git a/CMakeLists.txt b/CMakeLists.txt index c5150745b6..200d836fe1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -436,7 +436,10 @@ set(LIBOPENMC_FORTRAN_SRC ) set(LIBOPENMC_CXX_SRC src/random_lcg.h - src/random_lcg.cpp) + src/random_lcg.cpp + src/surface_header.C + src/pugixml/pugixml.hpp + src/pugixml/pugixml.cpp) add_library(libopenmc SHARED ${LIBOPENMC_FORTRAN_SRC} ${LIBOPENMC_CXX_SRC}) set_target_properties(libopenmc PROPERTIES OUTPUT_NAME openmc) add_executable(${program} src/main.F90) diff --git a/src/geometry.F90 b/src/geometry.F90 index ced62e6813..bc1eca2ae9 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -10,8 +10,33 @@ module geometry use stl_vector, only: VectorInt use string, only: to_str + use, intrinsic :: ISO_C_BINDING + implicit none + interface + function surface_sense_c(surf_ind, xyz, uvw) & + bind(C, name='surface_sense') result(sense) + use ISO_C_BINDING + implicit none + integer(C_INT), value :: surf_ind; + real(C_DOUBLE) :: xyz(3); + real(C_DOUBLE) :: uvw(3); + logical(C_BOOL) :: sense; + end function surface_sense_c + + function surface_distance_c(surf_ind, xyz, uvw, coincident) & + bind(C, name='surface_distance') result(d) + use ISO_C_BINDING + implicit none + integer(C_INT), value :: surf_ind; + real(C_DOUBLE) :: xyz(3); + real(C_DOUBLE) :: uvw(3); + logical(C_BOOL), value :: coincident; + real(C_DOUBLE) :: d; + end function surface_distance_c + end interface + contains !=============================================================================== @@ -28,7 +53,8 @@ contains ! expression using a stack, similar to how a RPN calculator would work. !=============================================================================== - pure function cell_contains(c, p) result(in_cell) + !pure function cell_contains(c, p) result(in_cell) + function cell_contains(c, p) result(in_cell) type(Cell), intent(in) :: c type(Particle), intent(in) :: p logical :: in_cell @@ -40,7 +66,8 @@ contains end if end function cell_contains - pure function simple_cell_contains(c, p) result(in_cell) + !pure function simple_cell_contains(c, p) result(in_cell) + function simple_cell_contains(c, p) result(in_cell) type(Cell), intent(in) :: c type(Particle), intent(in) :: p logical :: in_cell @@ -48,6 +75,7 @@ contains integer :: i integer :: token logical :: actual_sense ! sense of particle wrt surface + logical :: alt_sense in_cell = .true. do i = 1, size(c%rpn) @@ -65,6 +93,15 @@ contains else actual_sense = surfaces(abs(token))%obj%sense(& p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) + alt_sense = surface_sense_c(abs(token)-1, & + p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) + if (actual_sense .neqv. alt_sense) then + write(*, *) surfaces(abs(token)) % obj % id + write(*, *) p % coord (p % n_coord) % xyz + write(*, *) p % coord (p % n_coord) % uvw + write(*, *) actual_sense, alt_sense + call fatal_error("") + end if if (actual_sense .neqv. (token > 0)) then in_cell = .false. exit @@ -484,6 +521,7 @@ contains type(Cell), pointer :: c class(Surface), pointer :: surf class(Lattice), pointer :: lat + real(8) :: d_alt ! inialize distance to infinity (huge) dist = INFINITY @@ -519,6 +557,11 @@ contains ! Calculate distance to surface surf => surfaces(index_surf) % obj d = surf % distance(p % coord(j) % xyz, p % coord(j) % uvw, coincident) + d_alt = surface_distance_c(index_surf-1, p % coord(j) % xyz, & + p % coord(j) % uvw, logical(coincident, kind=C_BOOL)) + if (d /= d_alt) then + write(*, *) d, d_alt + end if ! Check if calculated distance is new minimum if (d < d_surf) then diff --git a/src/input_xml.F90 b/src/input_xml.F90 index bd56422cb5..4994ff76bc 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -48,6 +48,14 @@ module input_xml implicit none save + interface + subroutine read_surfaces(node_ptr) bind(C, name='read_surfaces') + use ISO_C_BINDING + implicit none + type(C_PTR) :: node_ptr + end subroutine read_surfaces + end interface + contains !=============================================================================== @@ -966,6 +974,7 @@ contains ! get pointer to list of xml call get_node_list(root, "surface", node_surf_list) + call read_surfaces(root % ptr) ! Get number of tags n_surfaces = size(node_surf_list) diff --git a/src/surface_header.C b/src/surface_header.C new file mode 100644 index 0000000000..08287da88a --- /dev/null +++ b/src/surface_header.C @@ -0,0 +1,280 @@ +#include // For strcmp +#include +#include // For numeric_limits +#include // For fabs +#include "pugixml/pugixml.hpp" + +//============================================================================== +// Constants +//============================================================================== + +const double FP_COINCIDENT = 1e-12; +const double INFTY = std::numeric_limits::max(); + +//============================================================================== +// Global array of surfaces +//============================================================================== + +class Surface; +Surface **surfaces_c; + +//============================================================================== +// SURFACE type defines a first- or second-order surface that can be used to +// construct closed volumes (cells) +//============================================================================== + +class Surface +{ + int id; // Unique ID + int neighbor_pos[], // List of cells on positive side + neighbor_neg[]; // List of cells on negative side + int bc; // Boundary condition + //TODO: swith that zero to a NONE constant. + int i_periodic = 0; // Index of corresponding periodic surface + char name[104]; // User-defined name + +public: + bool sense(double xyz[3], double uvw[3]); + void reflect(double xyz[3], double uvw[3]); + virtual double evaluate(double xyz[3]) = 0; + virtual double distance(double xyz[3], double uvw[3], bool coincident) = 0; + virtual void normal(double xyz[3], double uvw[3]) = 0; +}; + +bool +Surface::sense(double xyz[3], double uvw[3]) +{ + // Evaluate the surface equation at the particle's coordinates to determine + // which side the particle is on. + const double f = evaluate(xyz); + + // Check which side of surface the point is on. + bool s; + if (fabs(f) < FP_COINCIDENT) + { + // Particle may be coincident with this surface. To determine the sense, we + // look at the direction of the particle relative to the surface normal (by + // default in the positive direction) via their dot product. + double norm[3]; + normal(xyz, norm); + s = (uvw[0] * norm[0] + uvw[1] * norm[1] + uvw[2] * norm[2] > 0.0); + } + else + { + s = (f > 0.0); + } + return s; +} + +void +Surface::reflect(double xyz[3], double uvw[3]) +{ + + // Determine projection of direction onto normal and squared magnitude of + // normal. + double norm[3]; + normal(xyz, norm); + const double projection = norm[0]*uvw[0] + norm[1]*uvw[1] + norm[2]*uvw[2]; + const double magnitude = norm[0]*norm[0] + norm[1]*norm[1] + norm[2]*norm[2]; + + // Reflect direction according to normal. + uvw[0] -= 2.0 * projection / magnitude * norm[0]; + uvw[1] -= 2.0 * projection / magnitude * norm[1]; + uvw[2] -= 2.0 * projection / magnitude * norm[2]; +} + +//============================================================================== + +class SurfaceZPlane : public Surface +{ + double z0; +public: + SurfaceZPlane(pugi::xml_node surf_node); + double evaluate(double xyz[3]); + double distance(double xyz[3], double uvw[3], bool coincident); + void normal(double xyz[3], double uvw[3]); +}; + +SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) +{ + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf", &z0); + if (stat != 1) + { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +double +SurfaceZPlane::evaluate(double xyz[3]) +{ + double f = xyz[2] - z0; + return f; +} + +double +SurfaceZPlane::distance(double xyz[3], double uvw[3], bool coincident) +{ + double f = z0 - xyz[2]; + double d; + if (coincident or fabs(f) < FP_COINCIDENT or uvw[2] == 0.0) + { + d = INFTY; + } + else + { + d = f / uvw[2]; + if (d < 0.0) d = INFTY; + } + return d; +} + +void +SurfaceZPlane::normal(double xyz[3], double uvw[3]) +{ + uvw[0] = 0.0; + uvw[1] = 0.0; + uvw[2] = 1.0; +} + +//============================================================================== + +class SurfaceZCylinder : public Surface +{ + double x0, y0, r; +public: + SurfaceZCylinder(pugi::xml_node surf_node); + double evaluate(double xyz[3]); + double distance(double xyz[3], double uvw[3], bool coincident); + void normal(double xyz[3], double uvw[3]); +}; + +SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) +{ + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &y0, &r); + if (stat != 3) + { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +double +SurfaceZCylinder::evaluate(double xyz[3]) +{ + const double x = xyz[0] - x0; + const double y = xyz[1] - y0; + double f = x*x + y*y - r*r; + return f; +} + +double +SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) +{ + double a = 1.0 - uvw[2]*uvw[2]; // u^2 + v^2 + + if (a == 0.0) return INFTY; + + double x = xyz[0] - x0; + double y = xyz[1] - y0; + double k = x*uvw[0] + y*uvw[1]; + double c = x*x + y*y - r*r; + double quad = k*k - a*c; + + if (quad < 0.0) + { + // No intersection with cylinder. + return INFTY; + } + else if (coincident or fabs(c) < FP_COINCIDENT) + { + // Particle is on the cylinder, thus one distance is positive/negative + // and the other is zero. The sign of k determines if we are facing in or + // out. + if (k >= 0.0) return INFTY; + else return (-k + sqrt(quad)) / a; + } + else if (c < 0.0) + { + // Particle is inside the cylinder, thus one distance must be negative + // and one must be positive. The positive distance will be the one with + // negative sign on sqrt(quad) + return (-k + sqrt(quad)) / a; + } + else + { + // Particle is outside the cylinder, thus both distances are either + // positive or negative. If positive, the smaller distance is the one + // with positive sign on sqrt(quad) + + double d = (-k - sqrt(quad)) / a; + if (d < 0.0) return INFTY; + return d; + } +} + +void +SurfaceZCylinder::normal(double xyz[3], double uvw[3]) +{ + uvw[0] = 2.0 * (xyz[0] - x0); + uvw[1] = 2.0 * (xyz[1] - y0); + uvw[2] = 0.0; +} + +//============================================================================== + +extern "C" void +read_surfaces(pugi::xml_node *node) +{ + // Count the number of surfaces. + int n_surfaces = 0; + for (pugi::xml_node surf_node = node->child("surface"); surf_node; + surf_node = surf_node.next_sibling("surface")) + { + n_surfaces += 1; + } + + // Allocate the array of Surface pointers. + surfaces_c = new Surface* [n_surfaces]; + + // Loop over XML surface elements and populate the array. + { + pugi::xml_node surf_node; + int i_surf; + for (surf_node = node->child("surface"), i_surf = 0; surf_node; + surf_node = surf_node.next_sibling("surface"), i_surf++) + { + if (surf_node.attribute("type")) + { + const pugi::char_t *surf_type = surf_node.attribute("type").value(); + if (strcmp(surf_type, "z-cylinder") == 0) + { + surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); + } + else if (strcmp(surf_type, "z-plane") == 0) + { + surfaces_c[i_surf] = new SurfaceZPlane(surf_node); + } + else + { + std::cout << "Call error or handle uppercase here!" << std::endl; + std::cout << surf_type << std::endl; + } + } + } + } +} + +//============================================================================== + +extern "C" bool +surface_sense(int surf_ind, double xyz[3], double uvw[3]) +{ + return surfaces_c[surf_ind]->sense(xyz, uvw); +} + +extern "C" double +surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) +{ + return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); +} From c5708e6932b37f34a29274dbc6c98a34e74c66cf Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Thu, 18 Jan 2018 21:16:50 -0500 Subject: [PATCH 011/212] Move brackets to match proposed C++ styleguide --- src/surface_header.C | 90 +++++++++++++++----------------------------- 1 file changed, 30 insertions(+), 60 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 08287da88a..34ac7cf336 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -23,8 +23,7 @@ Surface **surfaces_c; // construct closed volumes (cells) //============================================================================== -class Surface -{ +class Surface { int id; // Unique ID int neighbor_pos[], // List of cells on positive side neighbor_neg[]; // List of cells on negative side @@ -42,34 +41,28 @@ public: }; bool -Surface::sense(double xyz[3], double uvw[3]) -{ +Surface::sense(double xyz[3], double uvw[3]) { // Evaluate the surface equation at the particle's coordinates to determine // which side the particle is on. const double f = evaluate(xyz); // Check which side of surface the point is on. bool s; - if (fabs(f) < FP_COINCIDENT) - { + if (fabs(f) < FP_COINCIDENT) { // Particle may be coincident with this surface. To determine the sense, we // look at the direction of the particle relative to the surface normal (by // default in the positive direction) via their dot product. double norm[3]; normal(xyz, norm); s = (uvw[0] * norm[0] + uvw[1] * norm[1] + uvw[2] * norm[2] > 0.0); - } - else - { + } else { s = (f > 0.0); } return s; } void -Surface::reflect(double xyz[3], double uvw[3]) -{ - +Surface::reflect(double xyz[3], double uvw[3]) { // Determine projection of direction onto normal and squared magnitude of // normal. double norm[3]; @@ -85,8 +78,7 @@ Surface::reflect(double xyz[3], double uvw[3]) //============================================================================== -class SurfaceZPlane : public Surface -{ +class SurfaceZPlane : public Surface { double z0; public: SurfaceZPlane(pugi::xml_node surf_node); @@ -95,26 +87,22 @@ public: void normal(double xyz[3], double uvw[3]); }; -SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) -{ +SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) { const char *coeffs = surf_node.attribute("coeffs").value(); int stat = sscanf(coeffs, "%lf", &z0); - if (stat != 1) - { + if (stat != 1) { std::cout << "Something went wrong reading surface coeffs!" << std::endl; } } double -SurfaceZPlane::evaluate(double xyz[3]) -{ +SurfaceZPlane::evaluate(double xyz[3]) { double f = xyz[2] - z0; return f; } double -SurfaceZPlane::distance(double xyz[3], double uvw[3], bool coincident) -{ +SurfaceZPlane::distance(double xyz[3], double uvw[3], bool coincident) { double f = z0 - xyz[2]; double d; if (coincident or fabs(f) < FP_COINCIDENT or uvw[2] == 0.0) @@ -130,8 +118,7 @@ SurfaceZPlane::distance(double xyz[3], double uvw[3], bool coincident) } void -SurfaceZPlane::normal(double xyz[3], double uvw[3]) -{ +SurfaceZPlane::normal(double xyz[3], double uvw[3]) { uvw[0] = 0.0; uvw[1] = 0.0; uvw[2] = 1.0; @@ -139,8 +126,7 @@ SurfaceZPlane::normal(double xyz[3], double uvw[3]) //============================================================================== -class SurfaceZCylinder : public Surface -{ +class SurfaceZCylinder : public Surface { double x0, y0, r; public: SurfaceZCylinder(pugi::xml_node surf_node); @@ -149,19 +135,16 @@ public: void normal(double xyz[3], double uvw[3]); }; -SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) -{ +SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { const char *coeffs = surf_node.attribute("coeffs").value(); int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &y0, &r); - if (stat != 3) - { + if (stat != 3) { std::cout << "Something went wrong reading surface coeffs!" << std::endl; } } double -SurfaceZCylinder::evaluate(double xyz[3]) -{ +SurfaceZCylinder::evaluate(double xyz[3]) { const double x = xyz[0] - x0; const double y = xyz[1] - y0; double f = x*x + y*y - r*r; @@ -169,8 +152,7 @@ SurfaceZCylinder::evaluate(double xyz[3]) } double -SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) -{ +SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) { double a = 1.0 - uvw[2]*uvw[2]; // u^2 + v^2 if (a == 0.0) return INFTY; @@ -181,32 +163,27 @@ SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) double c = x*x + y*y - r*r; double quad = k*k - a*c; - if (quad < 0.0) - { + if (quad < 0.0) { // No intersection with cylinder. return INFTY; - } - else if (coincident or fabs(c) < FP_COINCIDENT) - { + + } else if (coincident or fabs(c) < FP_COINCIDENT) { // Particle is on the cylinder, thus one distance is positive/negative // and the other is zero. The sign of k determines if we are facing in or // out. if (k >= 0.0) return INFTY; else return (-k + sqrt(quad)) / a; - } - else if (c < 0.0) - { + + } else if (c < 0.0) { // Particle is inside the cylinder, thus one distance must be negative // and one must be positive. The positive distance will be the one with // negative sign on sqrt(quad) return (-k + sqrt(quad)) / a; - } - else - { + + } else { // Particle is outside the cylinder, thus both distances are either // positive or negative. If positive, the smaller distance is the one // with positive sign on sqrt(quad) - double d = (-k - sqrt(quad)) / a; if (d < 0.0) return INFTY; return d; @@ -214,8 +191,7 @@ SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) } void -SurfaceZCylinder::normal(double xyz[3], double uvw[3]) -{ +SurfaceZCylinder::normal(double xyz[3], double uvw[3]) { uvw[0] = 2.0 * (xyz[0] - x0); uvw[1] = 2.0 * (xyz[1] - y0); uvw[2] = 0.0; @@ -224,13 +200,11 @@ SurfaceZCylinder::normal(double xyz[3], double uvw[3]) //============================================================================== extern "C" void -read_surfaces(pugi::xml_node *node) -{ +read_surfaces(pugi::xml_node *node) { // Count the number of surfaces. int n_surfaces = 0; for (pugi::xml_node surf_node = node->child("surface"); surf_node; - surf_node = surf_node.next_sibling("surface")) - { + surf_node = surf_node.next_sibling("surface")) { n_surfaces += 1; } @@ -242,10 +216,8 @@ read_surfaces(pugi::xml_node *node) pugi::xml_node surf_node; int i_surf; for (surf_node = node->child("surface"), i_surf = 0; surf_node; - surf_node = surf_node.next_sibling("surface"), i_surf++) - { - if (surf_node.attribute("type")) - { + surf_node = surf_node.next_sibling("surface"), i_surf++) { + if (surf_node.attribute("type")) { const pugi::char_t *surf_type = surf_node.attribute("type").value(); if (strcmp(surf_type, "z-cylinder") == 0) { @@ -268,13 +240,11 @@ read_surfaces(pugi::xml_node *node) //============================================================================== extern "C" bool -surface_sense(int surf_ind, double xyz[3], double uvw[3]) -{ +surface_sense(int surf_ind, double xyz[3], double uvw[3]) { return surfaces_c[surf_ind]->sense(xyz, uvw); } extern "C" double -surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) -{ +surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) { return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); } From 4cd335f6a93b21d5010e9f9981093a05a5d8435e Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 11 Aug 2017 22:05:33 -0400 Subject: [PATCH 012/212] Add x-, y- planes and cylinders to C++ Introudce templated generic functions to reduce code repetition for surfaces --- src/surface_header.C | 358 +++++++++++++++++++++++++++++++++---------- 1 file changed, 276 insertions(+), 82 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 34ac7cf336..f62be77ab3 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -33,36 +33,34 @@ class Surface { char name[104]; // User-defined name public: - bool sense(double xyz[3], double uvw[3]); - void reflect(double xyz[3], double uvw[3]); - virtual double evaluate(double xyz[3]) = 0; - virtual double distance(double xyz[3], double uvw[3], bool coincident) = 0; - virtual void normal(double xyz[3], double uvw[3]) = 0; + bool sense(const double xyz[3], const double uvw[3]) const; + void reflect(const double xyz[3], double uvw[3]) const; + virtual double evaluate(const double xyz[3]) const = 0; + virtual double distance(const double xyz[3], const double uvw[3], + bool coincident) const = 0; + virtual void normal(const double xyz[3], double uvw[3]) const = 0; }; bool -Surface::sense(double xyz[3], double uvw[3]) { +Surface::sense(const double xyz[3], const double uvw[3]) const { // Evaluate the surface equation at the particle's coordinates to determine // which side the particle is on. const double f = evaluate(xyz); // Check which side of surface the point is on. - bool s; if (fabs(f) < FP_COINCIDENT) { // Particle may be coincident with this surface. To determine the sense, we // look at the direction of the particle relative to the surface normal (by // default in the positive direction) via their dot product. double norm[3]; normal(xyz, norm); - s = (uvw[0] * norm[0] + uvw[1] * norm[1] + uvw[2] * norm[2] > 0.0); - } else { - s = (f > 0.0); + return uvw[0] * norm[0] + uvw[1] * norm[1] + uvw[2] * norm[2] > 0.0; } - return s; + return f > 0.0; } void -Surface::reflect(double xyz[3], double uvw[3]) { +Surface::reflect(const double xyz[3], double uvw[3]) const { // Determine projection of direction onto normal and squared magnitude of // normal. double norm[3]; @@ -76,15 +74,113 @@ Surface::reflect(double xyz[3], double uvw[3]) { uvw[2] -= 2.0 * projection / magnitude * norm[2]; } +//============================================================================== +// Generic functions for X-, Y-, and Z-, planes +//============================================================================== + +template double +axis_aligned_plane_evaluate(const double xyz[3], double offset) { + return xyz[i] - offset;} + +template double +axis_aligned_plane_distance(const double xyz[3], const double uvw[3], + bool coincident, double offset) { + const double f = offset - xyz[i]; + if (coincident or fabs(f) < FP_COINCIDENT or uvw[i] == 0.0) return INFTY; + const double d = f / uvw[i]; + if (d < 0.0) return INFTY; + return d; +} + +template void +axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { + uvw[i1] = 1.0; + uvw[i2] = 0.0; + uvw[i3] = 0.0; +} + +//============================================================================== +// SurfaceXPlane +//============================================================================== + +class SurfaceXPlane : public Surface { + double x0; +public: + SurfaceXPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + const bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf", &x0); + if (stat != 1) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double SurfaceXPlane::evaluate(const double xyz[3]) const { + return axis_aligned_plane_evaluate<0>(xyz, x0); +} + +inline double SurfaceXPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const { + return axis_aligned_plane_distance<0>(xyz, uvw, coincident, x0); +} + +inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); +} + +//============================================================================== +// SurfaceYPlane +//============================================================================== + +class SurfaceYPlane : public Surface { + double y0; +public: + SurfaceYPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf", &y0); + if (stat != 1) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double SurfaceYPlane::evaluate(const double xyz[3]) const { + return axis_aligned_plane_evaluate<1>(xyz, y0); +} + +inline double SurfaceYPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const { + return axis_aligned_plane_distance<1>(xyz, uvw, coincident, y0); +} + +inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); +} + +//============================================================================== +// SurfaceZPlane //============================================================================== class SurfaceZPlane : public Surface { double z0; public: SurfaceZPlane(pugi::xml_node surf_node); - double evaluate(double xyz[3]); - double distance(double xyz[3], double uvw[3], bool coincident); - void normal(double xyz[3], double uvw[3]); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; }; SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) { @@ -95,73 +191,49 @@ SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) { } } -double -SurfaceZPlane::evaluate(double xyz[3]) { - double f = xyz[2] - z0; - return f; +inline double SurfaceZPlane::evaluate(const double xyz[3]) const { + return axis_aligned_plane_evaluate<2>(xyz, z0); } -double -SurfaceZPlane::distance(double xyz[3], double uvw[3], bool coincident) { - double f = z0 - xyz[2]; - double d; - if (coincident or fabs(f) < FP_COINCIDENT or uvw[2] == 0.0) - { - d = INFTY; - } - else - { - d = f / uvw[2]; - if (d < 0.0) d = INFTY; - } - return d; +inline double SurfaceZPlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const { + return axis_aligned_plane_distance<2>(xyz, uvw, coincident, z0); } -void -SurfaceZPlane::normal(double xyz[3], double uvw[3]) { - uvw[0] = 0.0; - uvw[1] = 0.0; - uvw[2] = 1.0; +inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); } +//============================================================================== +// SurfacePlane //============================================================================== -class SurfaceZCylinder : public Surface { - double x0, y0, r; -public: - SurfaceZCylinder(pugi::xml_node surf_node); - double evaluate(double xyz[3]); - double distance(double xyz[3], double uvw[3], bool coincident); - void normal(double xyz[3], double uvw[3]); -}; +// TODO -SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &y0, &r); - if (stat != 3) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } +//============================================================================== +// Generic functions for X-, Y-, and Z-, cylinders +//============================================================================== + +template double +axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, + double offset2, double radius) { + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + return xyz1*xyz1 + xyz2*xyz2 - radius*radius; } -double -SurfaceZCylinder::evaluate(double xyz[3]) { - const double x = xyz[0] - x0; - const double y = xyz[1] - y0; - double f = x*x + y*y - r*r; - return f; -} - -double -SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) { - double a = 1.0 - uvw[2]*uvw[2]; // u^2 + v^2 +template double +axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], + double offset1, double offset2, double radius, bool coincident) { + const double a = 1.0 - uvw[i1]*uvw[i1]; // u^2 + v^2 if (a == 0.0) return INFTY; - double x = xyz[0] - x0; - double y = xyz[1] - y0; - double k = x*uvw[0] + y*uvw[1]; - double c = x*x + y*y - r*r; - double quad = k*k - a*c; + const double xyz2 = xyz[i2] - offset1; + const double xyz3 = xyz[i3] - offset2; + const double k = xyz2 * uvw[i2] + xyz3 * uvw[i3]; + const double c = xyz2*xyz2 + xyz3*xyz3 - radius*radius; + const double quad = k*k - a*c; if (quad < 0.0) { // No intersection with cylinder. @@ -190,11 +262,123 @@ SurfaceZCylinder::distance(double xyz[3], double uvw[3], bool coincident) { } } -void -SurfaceZCylinder::normal(double xyz[3], double uvw[3]) { - uvw[0] = 2.0 * (xyz[0] - x0); - uvw[1] = 2.0 * (xyz[1] - y0); - uvw[2] = 0.0; +template void +axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, + double offset2) { + uvw[i2] = 2.0 * (xyz[i2] - offset1); + uvw[i3] = 2.0 * (xyz[i3] - offset2); + uvw[i1] = 0.0; +} + +//============================================================================== +// SurfaceXCylinder +//============================================================================== + +class SurfaceXCylinder : public Surface { + double y0, z0, r; +public: + SurfaceXCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf", &y0, &z0, &r); + if (stat != 3) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double +SurfaceXCylinder::evaluate(const double xyz[3]) const { + return axis_aligned_cylinder_evaluate<1, 2>(xyz, y0, z0, r); +} + +inline double SurfaceXCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cylinder_distance<0, 1, 2>(xyz, uvw, coincident, y0, z0, + r); +} + +inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cylinder_normal<0, 1, 2>(xyz, uvw, y0, z0); +} + +//============================================================================== +// SurfaceYCylinder +//============================================================================== + +class SurfaceYCylinder : public Surface { + double x0, z0, r; +public: + SurfaceYCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &z0, &r); + if (stat != 3) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double +SurfaceYCylinder::evaluate(const double xyz[3]) const { + return axis_aligned_cylinder_evaluate<0, 2>(xyz, x0, z0, r); +} + +inline double SurfaceYCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cylinder_distance<1, 0, 2>(xyz, uvw, coincident, x0, z0, + r); +} + +inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cylinder_normal<1, 0, 2>(xyz, uvw, x0, z0); +} + +//============================================================================== +// SurfaceZCylinder +//============================================================================== + +class SurfaceZCylinder : public Surface { + double x0, y0, r; +public: + SurfaceZCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &y0, &r); + if (stat != 3) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double +SurfaceZCylinder::evaluate(const double xyz[3]) const { + return axis_aligned_cylinder_evaluate<0, 1>(xyz, x0, y0, r); +} + +inline double SurfaceZCylinder::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cylinder_distance<2, 0, 1>(xyz, uvw, coincident, x0, y0, + r); +} + +inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); } //============================================================================== @@ -219,16 +403,26 @@ read_surfaces(pugi::xml_node *node) { surf_node = surf_node.next_sibling("surface"), i_surf++) { if (surf_node.attribute("type")) { const pugi::char_t *surf_type = surf_node.attribute("type").value(); - if (strcmp(surf_type, "z-cylinder") == 0) - { - surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); - } - else if (strcmp(surf_type, "z-plane") == 0) - { + + if (strcmp(surf_type, "x-plane") == 0) { + surfaces_c[i_surf] = new SurfaceXPlane(surf_node); + + } else if (strcmp(surf_type, "y-plane") == 0) { + surfaces_c[i_surf] = new SurfaceYPlane(surf_node); + + } else if (strcmp(surf_type, "z-plane") == 0) { surfaces_c[i_surf] = new SurfaceZPlane(surf_node); - } - else - { + + } else if (strcmp(surf_type, "x-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); + + } else if (strcmp(surf_type, "y-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); + + } else if (strcmp(surf_type, "z-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); + + } else { std::cout << "Call error or handle uppercase here!" << std::endl; std::cout << surf_type << std::endl; } From 303ee3486e001e7ea3452775fc4ee142022b7320 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 11 Aug 2017 22:38:38 -0400 Subject: [PATCH 013/212] Add SurfaceSphere to C++ --- src/surface_header.C | 113 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 108 insertions(+), 5 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index f62be77ab3..42fb948af1 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -243,20 +243,23 @@ axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], // Particle is on the cylinder, thus one distance is positive/negative // and the other is zero. The sign of k determines if we are facing in or // out. - if (k >= 0.0) return INFTY; - else return (-k + sqrt(quad)) / a; + if (k >= 0.0) { + return INFTY; + } else { + return (-k + sqrt(quad)) / a; + } } else if (c < 0.0) { // Particle is inside the cylinder, thus one distance must be negative // and one must be positive. The positive distance will be the one with - // negative sign on sqrt(quad) + // negative sign on sqrt(quad). return (-k + sqrt(quad)) / a; } else { // Particle is outside the cylinder, thus both distances are either // positive or negative. If positive, the smaller distance is the one - // with positive sign on sqrt(quad) - double d = (-k - sqrt(quad)) / a; + // with positive sign on sqrt(quad). + const double d = (-k - sqrt(quad)) / a; if (d < 0.0) return INFTY; return d; } @@ -381,6 +384,103 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); } +//============================================================================== +// SurfaceSphere +//============================================================================== + +class SurfaceSphere : public Surface { + double x0, y0, z0, r; +public: + SurfaceSphere(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +double SurfaceSphere::evaluate(const double xyz[3]) const { + const double x = xyz[0] - x0; + const double y = xyz[1] - y0; + const double z = xyz[2] - z0; + return x*x + y*y + z*z - r*r; +} + +double SurfaceSphere::distance(const double xyz[3], const double uvw[3], + bool coincident) const { + const double x = xyz[0] - x0; + const double y = xyz[1] - y0; + const double z = xyz[2] - z0; + const double k = x*uvw[0] + y*uvw[1] + z*uvw[2]; + const double c = x*x + y*y + z*z - r*r; + const double quad = k*k - c; + + if (quad < 0.0) { + // No intersection with sphere. + return INFTY; + + } else if (coincident or fabs(c) < FP_COINCIDENT) { + // Particle is on the sphere, thus one distance is positive/negative and + // the other is zero. The sign of k determines if we are facing in or out. + if (k >= 0.0) { + return INFTY; + } else { + return -k + sqrt(quad); + } + + } else if (c < 0.0) { + // Particle is inside the sphere, thus one distance must be negative and + // one must be positive. The positive distance will be the one with + // negative sign on sqrt(quad) + return -k + sqrt(quad); + + } else { + // Particle is outside the sphere, thus both distances are either positive + // or negative. If positive, the smaller distance is the one with positive + // sign on sqrt(quad). + const double d = -k - sqrt(quad); + if (d < 0.0) return INFTY; + return d; + } +} + +inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const { + uvw[0] = 2.0 * (xyz[0] - x0); + uvw[1] = 2.0 * (xyz[1] - y0); + uvw[2] = 2.0 * (xyz[2] - z0); +} + +//============================================================================== +// SurfaceXCone +//============================================================================== + +// TODO + +//============================================================================== +// SurfaceYCone +//============================================================================== + +// TODO + +//============================================================================== +// SurfaceZCone +//============================================================================== + +// TODO + +//============================================================================== +// SurfaceQuadric +//============================================================================== + +// TODO + //============================================================================== extern "C" void @@ -422,6 +522,9 @@ read_surfaces(pugi::xml_node *node) { } else if (strcmp(surf_type, "z-cylinder") == 0) { surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); + } else if (strcmp(surf_type, "sphere") == 0) { + surfaces_c[i_surf] = new SurfaceSphere(surf_node); + } else { std::cout << "Call error or handle uppercase here!" << std::endl; std::cout << surf_type << std::endl; From 2d0938284b28db1e007797c2ad5368404d2fd6f2 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sat, 12 Aug 2017 17:29:44 -0400 Subject: [PATCH 014/212] Add remaining surfaces to C++ --- src/surface_header.C | 355 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 340 insertions(+), 15 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 42fb948af1..397be2cff2 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -75,7 +75,7 @@ Surface::reflect(const double xyz[3], double uvw[3]) const { } //============================================================================== -// Generic functions for X-, Y-, and Z-, planes +// Generic functions for x-, y-, and z-, planes //============================================================================== template double @@ -104,6 +104,7 @@ axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { //============================================================================== class SurfaceXPlane : public Surface { + // x = x0 double x0; public: SurfaceXPlane(pugi::xml_node surf_node); @@ -139,6 +140,7 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const { //============================================================================== class SurfaceYPlane : public Surface { + // y = y0 double y0; public: SurfaceYPlane(pugi::xml_node surf_node); @@ -174,6 +176,7 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const { //============================================================================== class SurfaceZPlane : public Surface { + // z = z0 double z0; public: SurfaceZPlane(pugi::xml_node surf_node); @@ -208,10 +211,53 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const { // SurfacePlane //============================================================================== -// TODO +class SurfacePlane : public Surface { + // Ax + By + Cz = D + double A, B, C, D; +public: + SurfacePlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + const bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfacePlane::SurfacePlane(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &A, &B, &C, &D); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +double +SurfacePlane::evaluate(const double xyz[3]) const { + return A*xyz[0] + B*xyz[1] + C*xyz[2] - D; +} + +double +SurfacePlane::distance(const double xyz[3], const double uvw[3], + bool coincident) const { + const double f = A*xyz[0] + B*xyz[1] + C*xyz[2] - D; + const double projection = A*uvw[0] + B*uvw[1] + C*uvw[2]; + if (coincident or fabs(f) < FP_COINCIDENT or projection == 0.0) { + return INFTY; + } else { + const double d = -f / projection; + if (d < 0.0) return INFTY; + return d; + } +} + +void +SurfacePlane::normal(const double xyz[3], double uvw[3]) const { + uvw[0] = A; + uvw[1] = B; + uvw[2] = C; +} //============================================================================== -// Generic functions for X-, Y-, and Z-, cylinders +// Generic functions for x-, y-, and z-, cylinders //============================================================================== template double @@ -224,9 +270,8 @@ axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, template double axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], - double offset1, double offset2, double radius, bool coincident) { + bool coincident, double offset1, double offset2, double radius) { const double a = 1.0 - uvw[i1]*uvw[i1]; // u^2 + v^2 - if (a == 0.0) return INFTY; const double xyz2 = xyz[i2] - offset1; @@ -277,7 +322,10 @@ axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, // SurfaceXCylinder //============================================================================== +// TODO: Test this implementation! + class SurfaceXCylinder : public Surface { + // (y - y0)^2 + (z - z0)^2 = R^2 double y0, z0, r; public: SurfaceXCylinder(pugi::xml_node surf_node); @@ -295,8 +343,7 @@ SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) { } } -inline double -SurfaceXCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceXCylinder::evaluate(const double xyz[3]) const { return axis_aligned_cylinder_evaluate<1, 2>(xyz, y0, z0, r); } @@ -314,7 +361,10 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const { // SurfaceYCylinder //============================================================================== +// TODO: Test this implementation! + class SurfaceYCylinder : public Surface { + // (x - x0)^2 + (z - z0)^2 = R^2 double x0, z0, r; public: SurfaceYCylinder(pugi::xml_node surf_node); @@ -332,8 +382,7 @@ SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) { } } -inline double -SurfaceYCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceYCylinder::evaluate(const double xyz[3]) const { return axis_aligned_cylinder_evaluate<0, 2>(xyz, x0, z0, r); } @@ -352,6 +401,7 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const { //============================================================================== class SurfaceZCylinder : public Surface { + // (x - x0)^2 + (y - y0)^2 = R^2 double x0, y0, r; public: SurfaceZCylinder(pugi::xml_node surf_node); @@ -369,8 +419,7 @@ SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { } } -inline double -SurfaceZCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceZCylinder::evaluate(const double xyz[3]) const { return axis_aligned_cylinder_evaluate<0, 1>(xyz, x0, y0, r); } @@ -389,6 +438,7 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { //============================================================================== class SurfaceSphere : public Surface { + // (x - x0)^2 + (y - y0)^2 + (z - z0)^2 = R^2 double x0, y0, z0, r; public: SurfaceSphere(pugi::xml_node surf_node); @@ -457,29 +507,289 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const { uvw[2] = 2.0 * (xyz[2] - z0); } +//============================================================================== +// Generic functions for x-, y-, and z-, cones +//============================================================================== + +template double +axis_aligned_cone_evaluate(const double xyz[3], double offset1, + double offset2, double offset3, double radius_sq) { + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + const double xyz3 = xyz[i3] - offset3; + return xyz2*xyz2 + xyz3*xyz3 - radius_sq*xyz1*xyz1; +} + +template double +axis_aligned_cone_distance(const double xyz[3], const double uvw[3], + bool coincident, double offset1, double offset2, double offset3, + double radius_sq) { + const double xyz1 = xyz[i1] - offset1; + const double xyz2 = xyz[i2] - offset2; + const double xyz3 = xyz[i3] - offset3; + const double a = uvw[i2]*uvw[i2] + uvw[i3]*uvw[i3] + - radius_sq*uvw[i1]*uvw[i1]; + const double k = xyz2*uvw[i2] + xyz3*uvw[i3] - radius_sq*xyz1*uvw[i1]; + const double c = xyz2*xyz2 + xyz3*xyz3 - radius_sq*xyz1*xyz1; + double quad = k*k - a*c; + + double d; + + if (quad < 0.0) { + // No intersection with cone. + return INFTY; + + } else if (coincident or fabs(c) < FP_COINCIDENT) { + // Particle is on the cone, thus one distance is positive/negative + // and the other is zero. The sign of k determines if we are facing in or + // out. + if (k >= 0.0) { + d = (-k - sqrt(quad)) / a; + } else { + d = (-k + sqrt(quad)) / a; + } + + } else { + // Calculate both solutions to the quadratic. + quad = sqrt(quad); + d = (-k - quad) / a; + const double b = (-k + quad) / a; + + // Determine the smallest positive solution. + if (d < 0.0) { + if (b > 0.0) d = b; + } else { + if (b > 0.0) { + if (b < d) d = b; + } + } + } + + // If the distance was negative, set boundary distance to infinity. + if (d <= 0.0) return INFTY; + return d; +} + +template void +axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, + double offset2, double offset3, double radius_sq) { + uvw[i1] = -2.0 * radius_sq * (xyz[i1] - offset1); + uvw[i2] = 2.0 * (xyz[i2] - offset2); + uvw[i3] = 2.0 * (xyz[i3] - offset3); +} + //============================================================================== // SurfaceXCone //============================================================================== -// TODO +// TODO: Test this implementation! + +class SurfaceXCone : public Surface { + // (y - y0)^2 + (z - z0)^2 = R^2*(x - x0)^2 + double x0, y0, z0, r_sq; +public: + SurfaceXCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double SurfaceXCone::evaluate(const double xyz[3]) const { + return axis_aligned_cone_evaluate<0, 1, 2>(xyz, x0, y0, z0, r_sq); +} + +inline double SurfaceXCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cone_distance<0, 1, 2>(xyz, uvw, coincident, x0, y0, z0, + r_sq); +} + +inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cone_normal<0, 1, 2>(xyz, uvw, x0, y0, z0, r_sq); +} //============================================================================== // SurfaceYCone //============================================================================== -// TODO +// TODO: Test this implementation! + +class SurfaceYCone : public Surface { + // (x - x0)^2 + (z - z0)^2 = R^2*(y - y0)^2 + double x0, y0, z0, r_sq; +public: + SurfaceYCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double SurfaceYCone::evaluate(const double xyz[3]) const { + return axis_aligned_cone_evaluate<1, 0, 2>(xyz, y0, x0, z0, r_sq); +} + +inline double SurfaceYCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cone_distance<1, 0, 2>(xyz, uvw, coincident, y0, x0, z0, + r_sq); +} + +inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cone_normal<1, 0, 2>(xyz, uvw, y0, x0, z0, r_sq); +} //============================================================================== // SurfaceZCone //============================================================================== -// TODO +class SurfaceZCone : public Surface { + // (x - x0)^2 + (y - y0)^2 = R^2*(z - z0)^2 + double x0, y0, z0, r_sq; +public: + SurfaceZCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +inline double SurfaceZCone::evaluate(const double xyz[3]) const { + return axis_aligned_cone_evaluate<2, 0, 1>(xyz, z0, x0, y0, r_sq); +} + +inline double SurfaceZCone::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + return axis_aligned_cone_distance<2, 0, 1>(xyz, uvw, coincident, z0, x0, y0, + r_sq); +} + +inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const { + axis_aligned_cone_normal<2, 0, 1>(xyz, uvw, z0, x0, y0, r_sq); +} //============================================================================== // SurfaceQuadric //============================================================================== -// TODO +class SurfaceQuadric : public Surface { + // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 + double A, B, C, D, E, F, G, H, J, K; +public: + SurfaceQuadric(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; +}; + +SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) { + const char *coeffs = surf_node.attribute("coeffs").value(); + int stat = sscanf(coeffs, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", + &A, &B, &C, &D, &E, &F, &G, &H, &J, &K); + if (stat != 10) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +double +SurfaceQuadric::evaluate(const double xyz[3]) const { + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + return x*(A*x + D*y + G) + + y*(B*y + E*z + H) + + z*(C*z + F*x + J) + K; +} + +double +SurfaceQuadric::distance(const double xyz[3], + const double uvw[3], bool coincident) const { + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + const double &u = uvw[0]; + const double &v = uvw[1]; + const double &w = uvw[2]; + + const double a = A*u*u + B*v*v + C*w*w + D*u*v + E*v*w + F*u*w; + const double k = (A*u*x + B*v*y + C*w*z + 0.5*(D*(u*y + v*x) + + E*(v*z + w*y) + F*(w*x + u*z) + G*u + H*v + J*w)); + const double c = A*x*x + B*y*y + C*z*z + D*x*y + E*y*z + F*x*z + G*x + H*y + + J*z + K; + double quad = k*k - a*c; + + double d; + + if (quad < 0.0) { + // No intersection with surface. + return INFTY; + + } else if (coincident or fabs(c) < FP_COINCIDENT) { + // Particle is on the surface, thus one distance is positive/negative and + // the other is zero. The sign of k determines which distance is zero and + // which is not. + if (k >= 0.0) { + d = (-k - sqrt(quad)) / a; + } else { + d = (-k + sqrt(quad)) / a; + } + + } else { + // Calculate both solutions to the quadratic. + quad = sqrt(quad); + d = (-k - quad) / a; + double b = (-k + quad) / a; + + // Determine the smallest positive solution. + if (d < 0.0) { + if (b > 0.0) d = b; + } else { + if (b > 0.0) { + if (b < d) d = b; + } + } + } + + // If the distance was negative, set boundary distance to infinity. + if (d <= 0.0) return INFTY; + return d; +} + +void +SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const { + const double &x = xyz[0]; + const double &y = xyz[1]; + const double &z = xyz[2]; + uvw[0] = 2.0*A*x + D*y + F*z + G; + uvw[1] = 2.0*B*y + D*x + E*z + H; + uvw[2] = 2.0*C*z + E*y + F*x + J; +} //============================================================================== @@ -513,6 +823,9 @@ read_surfaces(pugi::xml_node *node) { } else if (strcmp(surf_type, "z-plane") == 0) { surfaces_c[i_surf] = new SurfaceZPlane(surf_node); + } else if (strcmp(surf_type, "plane") == 0) { + surfaces_c[i_surf] = new SurfacePlane(surf_node); + } else if (strcmp(surf_type, "x-cylinder") == 0) { surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); @@ -525,6 +838,18 @@ read_surfaces(pugi::xml_node *node) { } else if (strcmp(surf_type, "sphere") == 0) { surfaces_c[i_surf] = new SurfaceSphere(surf_node); + } else if (strcmp(surf_type, "x-cone") == 0) { + surfaces_c[i_surf] = new SurfaceXCone(surf_node); + + } else if (strcmp(surf_type, "y-cone") == 0) { + surfaces_c[i_surf] = new SurfaceYCone(surf_node); + + } else if (strcmp(surf_type, "z-cone") == 0) { + surfaces_c[i_surf] = new SurfaceZCone(surf_node); + + } else if (strcmp(surf_type, "quadric") == 0) { + surfaces_c[i_surf] = new SurfaceQuadric(surf_node); + } else { std::cout << "Call error or handle uppercase here!" << std::endl; std::cout << surf_type << std::endl; From d4a1f1834b42c78f574525e564a09a537071b3ca Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sat, 2 Sep 2017 18:44:06 -0400 Subject: [PATCH 015/212] Handle both XML nodes and attributes in C++ surfs --- src/surface_header.C | 213 +++++++++++++++++++++++++------------------ 1 file changed, 123 insertions(+), 90 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 397be2cff2..3ac3d3c532 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -18,6 +18,82 @@ const double INFTY = std::numeric_limits::max(); class Surface; Surface **surfaces_c; +//============================================================================== +// Helper functions +//============================================================================== + +void read_coeffs(pugi::xml_node surf_node, double &c1) +{ + const char *coeffs; + if (surf_node.attribute("coeffs")) { + coeffs = surf_node.attribute("coeffs").value(); + } else if (surf_node.child("coeffs")) { + coeffs = surf_node.child_value("coeffs"); + } else { + std::cout << "ERROR: Found a surface with no coefficients" << std::endl; + } + + int stat = sscanf(coeffs, "%lf", &c1); + if (stat != 1) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3) +{ + const char *coeffs; + if (surf_node.attribute("coeffs")) { + coeffs = surf_node.attribute("coeffs").value(); + } else if (surf_node.child("coeffs")) { + coeffs = surf_node.child_value("coeffs"); + } else { + std::cout << "ERROR: Found a surface with no coefficients" << std::endl; + } + + int stat = sscanf(coeffs, "%lf %lf %lf", &c1, &c2, &c3); + if (stat != 3) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, + double &c4) +{ + const char *coeffs; + if (surf_node.attribute("coeffs")) { + coeffs = surf_node.attribute("coeffs").value(); + } else if (surf_node.child("coeffs")) { + coeffs = surf_node.child_value("coeffs"); + } else { + std::cout << "ERROR: Found a surface with no coefficients" << std::endl; + } + + int stat = sscanf(coeffs, "%lf %lf %lf %lf", &c1, &c2, &c3, &c4); + if (stat != 4) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + +void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, + double &c4, double &c5, double &c6, double &c7, double &c8, + double &c9, double &c10) +{ + const char *coeffs; + if (surf_node.attribute("coeffs")) { + coeffs = surf_node.attribute("coeffs").value(); + } else if (surf_node.child("coeffs")) { + coeffs = surf_node.child_value("coeffs"); + } else { + std::cout << "ERROR: Found a surface with no coefficients" << std::endl; + } + + int stat = sscanf(coeffs, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", + &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); + if (stat != 10) { + std::cout << "Something went wrong reading surface coeffs!" << std::endl; + } +} + //============================================================================== // SURFACE type defines a first- or second-order surface that can be used to // construct closed volumes (cells) @@ -115,11 +191,7 @@ public: }; SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf", &x0); - if (stat != 1) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0); } inline double SurfaceXPlane::evaluate(const double xyz[3]) const { @@ -151,11 +223,7 @@ public: }; SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf", &y0); - if (stat != 1) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, y0); } inline double SurfaceYPlane::evaluate(const double xyz[3]) const { @@ -187,11 +255,7 @@ public: }; SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf", &z0); - if (stat != 1) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, z0); } inline double SurfaceZPlane::evaluate(const double xyz[3]) const { @@ -223,11 +287,7 @@ public: }; SurfacePlane::SurfacePlane(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &A, &B, &C, &D); - if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, A, B, C, D); } double @@ -336,11 +396,7 @@ public: }; SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf", &y0, &z0, &r); - if (stat != 3) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, y0, z0, r); } inline double SurfaceXCylinder::evaluate(const double xyz[3]) const { @@ -375,11 +431,7 @@ public: }; SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &z0, &r); - if (stat != 3) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, z0, r); } inline double SurfaceYCylinder::evaluate(const double xyz[3]) const { @@ -412,11 +464,7 @@ public: }; SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf", &x0, &y0, &r); - if (stat != 3) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, y0, r); } inline double SurfaceZCylinder::evaluate(const double xyz[3]) const { @@ -449,11 +497,7 @@ public: }; SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r); - if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, y0, z0, r); } double SurfaceSphere::evaluate(const double xyz[3]) const { @@ -596,11 +640,7 @@ public: }; SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); - if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, y0, z0, r_sq); } inline double SurfaceXCone::evaluate(const double xyz[3]) const { @@ -635,11 +675,7 @@ public: }; SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); - if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, y0, z0, r_sq); } inline double SurfaceYCone::evaluate(const double xyz[3]) const { @@ -672,11 +708,7 @@ public: }; SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &x0, &y0, &z0, &r_sq); - if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, x0, y0, z0, r_sq); } inline double SurfaceZCone::evaluate(const double xyz[3]) const { @@ -709,12 +741,7 @@ public: }; SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) { - const char *coeffs = surf_node.attribute("coeffs").value(); - int stat = sscanf(coeffs, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", - &A, &B, &C, &D, &E, &F, &G, &H, &J, &K); - if (stat != 10) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; - } + read_coeffs(surf_node, A, B, C, D, E, F, G, H, J, K); } double @@ -811,49 +838,55 @@ read_surfaces(pugi::xml_node *node) { int i_surf; for (surf_node = node->child("surface"), i_surf = 0; surf_node; surf_node = surf_node.next_sibling("surface"), i_surf++) { + const pugi::char_t *surf_type; if (surf_node.attribute("type")) { - const pugi::char_t *surf_type = surf_node.attribute("type").value(); + surf_type = surf_node.attribute("type").value(); + } else if (surf_node.child("type")) { + surf_type = surf_node.child_value("type"); + } else { + std::cout << "ERROR: Found a surface with no type attribute/node" + << std::endl; + } - if (strcmp(surf_type, "x-plane") == 0) { - surfaces_c[i_surf] = new SurfaceXPlane(surf_node); + if (strcmp(surf_type, "x-plane") == 0) { + surfaces_c[i_surf] = new SurfaceXPlane(surf_node); - } else if (strcmp(surf_type, "y-plane") == 0) { - surfaces_c[i_surf] = new SurfaceYPlane(surf_node); + } else if (strcmp(surf_type, "y-plane") == 0) { + surfaces_c[i_surf] = new SurfaceYPlane(surf_node); - } else if (strcmp(surf_type, "z-plane") == 0) { - surfaces_c[i_surf] = new SurfaceZPlane(surf_node); + } else if (strcmp(surf_type, "z-plane") == 0) { + surfaces_c[i_surf] = new SurfaceZPlane(surf_node); - } else if (strcmp(surf_type, "plane") == 0) { - surfaces_c[i_surf] = new SurfacePlane(surf_node); + } else if (strcmp(surf_type, "plane") == 0) { + surfaces_c[i_surf] = new SurfacePlane(surf_node); - } else if (strcmp(surf_type, "x-cylinder") == 0) { - surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); + } else if (strcmp(surf_type, "x-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); - } else if (strcmp(surf_type, "y-cylinder") == 0) { - surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); + } else if (strcmp(surf_type, "y-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); - } else if (strcmp(surf_type, "z-cylinder") == 0) { - surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); + } else if (strcmp(surf_type, "z-cylinder") == 0) { + surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); - } else if (strcmp(surf_type, "sphere") == 0) { - surfaces_c[i_surf] = new SurfaceSphere(surf_node); + } else if (strcmp(surf_type, "sphere") == 0) { + surfaces_c[i_surf] = new SurfaceSphere(surf_node); - } else if (strcmp(surf_type, "x-cone") == 0) { - surfaces_c[i_surf] = new SurfaceXCone(surf_node); + } else if (strcmp(surf_type, "x-cone") == 0) { + surfaces_c[i_surf] = new SurfaceXCone(surf_node); - } else if (strcmp(surf_type, "y-cone") == 0) { - surfaces_c[i_surf] = new SurfaceYCone(surf_node); + } else if (strcmp(surf_type, "y-cone") == 0) { + surfaces_c[i_surf] = new SurfaceYCone(surf_node); - } else if (strcmp(surf_type, "z-cone") == 0) { - surfaces_c[i_surf] = new SurfaceZCone(surf_node); + } else if (strcmp(surf_type, "z-cone") == 0) { + surfaces_c[i_surf] = new SurfaceZCone(surf_node); - } else if (strcmp(surf_type, "quadric") == 0) { - surfaces_c[i_surf] = new SurfaceQuadric(surf_node); + } else if (strcmp(surf_type, "quadric") == 0) { + surfaces_c[i_surf] = new SurfaceQuadric(surf_node); - } else { - std::cout << "Call error or handle uppercase here!" << std::endl; - std::cout << surf_type << std::endl; - } + } else { + std::cout << "Call error or handle uppercase here!" << std::endl; + std::cout << surf_type << std::endl; } } } From 57dbb70d0c2b123cb2938eba7187204bd9fe9991 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sat, 2 Sep 2017 19:12:46 -0400 Subject: [PATCH 016/212] Add test code for C++ surface normals --- src/geometry.F90 | 18 ++++++++++++++++++ src/surface_header.C | 5 +++++ 2 files changed, 23 insertions(+) diff --git a/src/geometry.F90 b/src/geometry.F90 index bc1eca2ae9..8a449a284b 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -35,6 +35,15 @@ module geometry logical(C_BOOL), value :: coincident; real(C_DOUBLE) :: d; end function surface_distance_c + + subroutine surface_normal_c(surf_ind, xyz, uvw) & + bind(C, name='surface_normal') + use ISO_C_BINDING + implicit none + integer(C_INT), value :: surf_ind; + real(C_DOUBLE) :: xyz(3); + real(C_DOUBLE) :: uvw(3); + end subroutine surface_normal_c end interface contains @@ -76,6 +85,7 @@ contains integer :: token logical :: actual_sense ! sense of particle wrt surface logical :: alt_sense + real(8) :: uvw1(3), uvw2(3) in_cell = .true. do i = 1, size(c%rpn) @@ -102,6 +112,14 @@ contains write(*, *) actual_sense, alt_sense call fatal_error("") end if + uvw1 = surfaces(abs(token))%obj%normal(p%coord(p%n_coord)%xyz) + call surface_normal_c(abs(token)-1, p%coord(p%n_coord)%xyz, uvw2) + if (.not. all(uvw1 - uvw2 == ZERO)) then + write(*, *) "Surface normals don't match" + write(*, *) uvw1 + write(*, *) uvw2 + call fatal_error("") + end if if (actual_sense .neqv. (token > 0)) then in_cell = .false. exit diff --git a/src/surface_header.C b/src/surface_header.C index 3ac3d3c532..43209fc803 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -903,3 +903,8 @@ extern "C" double surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) { return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); } + +extern "C" void +surface_normal(int surf_ind, double xyz[3], double uvw[3]) { + return surfaces_c[surf_ind]->normal(xyz, uvw); +} From 3752fea1e9e3c45baf5aebf410ebc595f032596f Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sun, 3 Sep 2017 13:28:04 -0400 Subject: [PATCH 017/212] Use Doxygen-style comments for C++ surface code --- src/surface_header.C | 195 ++++++++++++++++++++++++++++--------------- 1 file changed, 126 insertions(+), 69 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 43209fc803..297335827c 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -1,9 +1,12 @@ #include // For strcmp -#include #include // For numeric_limits #include // For fabs + #include "pugixml/pugixml.hpp" +// DEBUGGING +#include + //============================================================================== // Constants //============================================================================== @@ -19,20 +22,24 @@ class Surface; Surface **surfaces_c; //============================================================================== -// Helper functions +// Helper functions for reading the "coeffs" node of an XML surface element //============================================================================== +const char* get_coeff_str(pugi::xml_node surf_node) +{ + if (surf_node.attribute("coeffs")) { + return surf_node.attribute("coeffs").value(); + } else if (surf_node.child("coeffs")) { + return surf_node.child_value("coeffs"); + } else { + std::cout << "ERROR: Found a surface with no coefficients" << std::endl; + return NULL; + } +} + void read_coeffs(pugi::xml_node surf_node, double &c1) { - const char *coeffs; - if (surf_node.attribute("coeffs")) { - coeffs = surf_node.attribute("coeffs").value(); - } else if (surf_node.child("coeffs")) { - coeffs = surf_node.child_value("coeffs"); - } else { - std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - } - + const char *coeffs = get_coeff_str(surf_node); int stat = sscanf(coeffs, "%lf", &c1); if (stat != 1) { std::cout << "Something went wrong reading surface coeffs!" << std::endl; @@ -41,15 +48,7 @@ void read_coeffs(pugi::xml_node surf_node, double &c1) void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3) { - const char *coeffs; - if (surf_node.attribute("coeffs")) { - coeffs = surf_node.attribute("coeffs").value(); - } else if (surf_node.child("coeffs")) { - coeffs = surf_node.child_value("coeffs"); - } else { - std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - } - + const char *coeffs = get_coeff_str(surf_node); int stat = sscanf(coeffs, "%lf %lf %lf", &c1, &c2, &c3); if (stat != 3) { std::cout << "Something went wrong reading surface coeffs!" << std::endl; @@ -59,15 +58,7 @@ void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3) void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, double &c4) { - const char *coeffs; - if (surf_node.attribute("coeffs")) { - coeffs = surf_node.attribute("coeffs").value(); - } else if (surf_node.child("coeffs")) { - coeffs = surf_node.child_value("coeffs"); - } else { - std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - } - + const char *coeffs = get_coeff_str(surf_node); int stat = sscanf(coeffs, "%lf %lf %lf %lf", &c1, &c2, &c3, &c4); if (stat != 4) { std::cout << "Something went wrong reading surface coeffs!" << std::endl; @@ -78,15 +69,7 @@ void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, double &c4, double &c5, double &c6, double &c7, double &c8, double &c9, double &c10) { - const char *coeffs; - if (surf_node.attribute("coeffs")) { - coeffs = surf_node.attribute("coeffs").value(); - } else if (surf_node.child("coeffs")) { - coeffs = surf_node.child_value("coeffs"); - } else { - std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - } - + const char *coeffs = get_coeff_str(surf_node); int stat = sscanf(coeffs, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); if (stat != 10) { @@ -95,25 +78,52 @@ void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, } //============================================================================== -// SURFACE type defines a first- or second-order surface that can be used to -// construct closed volumes (cells) +//! A geometry primitive used to define regions of 3D space. //============================================================================== class Surface { - int id; // Unique ID - int neighbor_pos[], // List of cells on positive side - neighbor_neg[]; // List of cells on negative side - int bc; // Boundary condition - //TODO: swith that zero to a NONE constant. - int i_periodic = 0; // Index of corresponding periodic surface - char name[104]; // User-defined name - public: + int id; //!< Unique ID + int neighbor_pos[], //!< List of cells on positive side + neighbor_neg[]; //!< List of cells on negative side + int bc; //!< Boundary condition + //TODO: switch that zero to a NONE constant. + int i_periodic = 0; //!< Index of corresponding periodic surface + char name[104]; //!< User-defined name + + //! Determine which side of a surface a point lies on. + //! @param xyz[3] The 3D Cartesian coordinate of a point. + //! @param uvw[3] A direction used to "break ties" and pick a sense when the + //! point is very close to the surface. + //! @return True if the point is on the "positive" side of the surface and + //! false otherwise. bool sense(const double xyz[3], const double uvw[3]) const; + + //! Determine the direction of a ray reflected from the surface. + //! @param xyz[3] The point at which the ray is incident. + //! @param uvw[3] A direction. This is both an input and an output parameter. + //! It specifies the icident direction on input and the reflected direction + //! on output. void reflect(const double xyz[3], double uvw[3]) const; + + //! Evaluate the equation describing the surface. + //! + //! Surfaces can be described by some function f(x, y, z) = 0. This member + //! function evaluates that mathematical function. + //! @param xyz[3] A 3D Cartesian coordinate. virtual double evaluate(const double xyz[3]) const = 0; + + //! Compute the distance between a point and the surface along a ray. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] The direction of the ray. + //! @param coincident A hint to the code that the given point should lie + //! exactly on the surface. virtual double distance(const double xyz[3], const double uvw[3], bool coincident) const = 0; + + //! Compute the local outward normal direction of the surface. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] This output argument provides the normal. virtual void normal(const double xyz[3], double uvw[3]) const = 0; }; @@ -151,13 +161,16 @@ Surface::reflect(const double xyz[3], double uvw[3]) const { } //============================================================================== -// Generic functions for x-, y-, and z-, planes +// Generic functions for x-, y-, and z-, planes. //============================================================================== +// The template parameter indicates the axis normal to the plane. template double axis_aligned_plane_evaluate(const double xyz[3], double offset) { - return xyz[i] - offset;} + return xyz[i] - offset; +} +// The template parameter indicates the axis normal to the plane. template double axis_aligned_plane_distance(const double xyz[3], const double uvw[3], bool coincident, double offset) { @@ -168,6 +181,8 @@ axis_aligned_plane_distance(const double xyz[3], const double uvw[3], return d; } +// The first template parameter indicates the axis normal to the plane. The +// other two parameters indicate the other two axes. template void axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { uvw[i1] = 1.0; @@ -177,10 +192,12 @@ axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { //============================================================================== // SurfaceXPlane +//! A plane perpendicular to the x-axis. +// +//! The plane is described by the equation \f$x - x_0 = 0\f$ //============================================================================== class SurfaceXPlane : public Surface { - // x = x0 double x0; public: SurfaceXPlane(pugi::xml_node surf_node); @@ -209,10 +226,12 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceYPlane +//! A plane perpendicular to the y-axis. +// +//! The plane is described by the equation \f$y - y_0 = 0\f$ //============================================================================== class SurfaceYPlane : public Surface { - // y = y0 double y0; public: SurfaceYPlane(pugi::xml_node surf_node); @@ -241,10 +260,12 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceZPlane +//! A plane perpendicular to the z-axis. +// +//! The plane is described by the equation \f$z - z_0 = 0\f$ //============================================================================== class SurfaceZPlane : public Surface { - // z = z0 double z0; public: SurfaceZPlane(pugi::xml_node surf_node); @@ -273,10 +294,12 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfacePlane +//! A general plane. +// +//! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ //============================================================================== class SurfacePlane : public Surface { - // Ax + By + Cz = D double A, B, C, D; public: SurfacePlane(pugi::xml_node surf_node); @@ -320,6 +343,9 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const { // Generic functions for x-, y-, and z-, cylinders //============================================================================== +// The template parameters indicate the axes perpendicular to the axis of the +// cylinder. offset1 and offset2 should correspond with i1 and i2, +// respectively. template double axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, double offset2, double radius) { @@ -328,6 +354,9 @@ axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, return xyz1*xyz1 + xyz2*xyz2 - radius*radius; } +// The first template parameter indicates which axis the cylinder is aligned to. +// The other two parameters indicate the other two axes. offset1 and offset2 +// should correspond with i2 and i3, respectively. template double axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], bool coincident, double offset1, double offset2, double radius) { @@ -370,6 +399,9 @@ axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], } } +// The first template parameter indicates which axis the cylinder is aligned to. +// The other two parameters indicate the other two axes. offset1 and offset2 +// should correspond with i2 and i3, respectively. template void axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, double offset2) { @@ -380,12 +412,13 @@ axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, //============================================================================== // SurfaceXCylinder +//! A cylinder aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -// TODO: Test this implementation! - class SurfaceXCylinder : public Surface { - // (y - y0)^2 + (z - z0)^2 = R^2 double y0, z0, r; public: SurfaceXCylinder(pugi::xml_node surf_node); @@ -415,12 +448,13 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceYCylinder +//! A cylinder aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -// TODO: Test this implementation! - class SurfaceYCylinder : public Surface { - // (x - x0)^2 + (z - z0)^2 = R^2 double x0, z0, r; public: SurfaceYCylinder(pugi::xml_node surf_node); @@ -450,10 +484,13 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceZCylinder +//! A cylinder aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ //============================================================================== class SurfaceZCylinder : public Surface { - // (x - x0)^2 + (y - y0)^2 = R^2 double x0, y0, r; public: SurfaceZCylinder(pugi::xml_node surf_node); @@ -483,10 +520,13 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceSphere +//! A sphere. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== class SurfaceSphere : public Surface { - // (x - x0)^2 + (y - y0)^2 + (z - z0)^2 = R^2 double x0, y0, z0, r; public: SurfaceSphere(pugi::xml_node surf_node); @@ -555,6 +595,9 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const { // Generic functions for x-, y-, and z-, cones //============================================================================== +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. template double axis_aligned_cone_evaluate(const double xyz[3], double offset1, double offset2, double offset3, double radius_sq) { @@ -564,6 +607,9 @@ axis_aligned_cone_evaluate(const double xyz[3], double offset1, return xyz2*xyz2 + xyz3*xyz3 - radius_sq*xyz1*xyz1; } +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. template double axis_aligned_cone_distance(const double xyz[3], const double uvw[3], bool coincident, double offset1, double offset2, double offset3, @@ -614,6 +660,9 @@ axis_aligned_cone_distance(const double xyz[3], const double uvw[3], return d; } +// The first template parameter indicates which axis the cone is aligned to. +// The other two parameters indicate the other two axes. offset1, offset2, +// and offset3 should correspond with i1, i2, and i3, respectively. template void axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, double offset2, double offset3, double radius_sq) { @@ -624,12 +673,13 @@ axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, //============================================================================== // SurfaceXCone +//! A cone aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ //============================================================================== -// TODO: Test this implementation! - class SurfaceXCone : public Surface { - // (y - y0)^2 + (z - z0)^2 = R^2*(x - x0)^2 double x0, y0, z0, r_sq; public: SurfaceXCone(pugi::xml_node surf_node); @@ -659,12 +709,13 @@ inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceYCone +//! A cone aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ //============================================================================== -// TODO: Test this implementation! - class SurfaceYCone : public Surface { - // (x - x0)^2 + (z - z0)^2 = R^2*(y - y0)^2 double x0, y0, z0, r_sq; public: SurfaceYCone(pugi::xml_node surf_node); @@ -694,10 +745,13 @@ inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceZCone +//! A cone aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ //============================================================================== class SurfaceZCone : public Surface { - // (x - x0)^2 + (y - y0)^2 = R^2*(z - z0)^2 double x0, y0, z0, r_sq; public: SurfaceZCone(pugi::xml_node surf_node); @@ -727,6 +781,9 @@ inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const { //============================================================================== // SurfaceQuadric +//! A general surface described by a quadratic equation. +// +//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ //============================================================================== class SurfaceQuadric : public Surface { From 72cb25e6776280fef9eb4d42e6cf712a9a36cf91 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Mon, 11 Sep 2017 16:42:40 -0400 Subject: [PATCH 018/212] Use consistent brace placement in C++ --- src/surface_header.C | 228 ++++++++++++++++++++++++++++--------------- 1 file changed, 152 insertions(+), 76 deletions(-) diff --git a/src/surface_header.C b/src/surface_header.C index 297335827c..6992c2e2ac 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -81,7 +81,8 @@ void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, //! A geometry primitive used to define regions of 3D space. //============================================================================== -class Surface { +class Surface +{ public: int id; //!< Unique ID int neighbor_pos[], //!< List of cells on positive side @@ -128,7 +129,8 @@ public: }; bool -Surface::sense(const double xyz[3], const double uvw[3]) const { +Surface::sense(const double xyz[3], const double uvw[3]) const +{ // Evaluate the surface equation at the particle's coordinates to determine // which side the particle is on. const double f = evaluate(xyz); @@ -146,7 +148,8 @@ Surface::sense(const double xyz[3], const double uvw[3]) const { } void -Surface::reflect(const double xyz[3], double uvw[3]) const { +Surface::reflect(const double xyz[3], double uvw[3]) const +{ // Determine projection of direction onto normal and squared magnitude of // normal. double norm[3]; @@ -166,14 +169,16 @@ Surface::reflect(const double xyz[3], double uvw[3]) const { // The template parameter indicates the axis normal to the plane. template double -axis_aligned_plane_evaluate(const double xyz[3], double offset) { +axis_aligned_plane_evaluate(const double xyz[3], double offset) +{ return xyz[i] - offset; } // The template parameter indicates the axis normal to the plane. template double axis_aligned_plane_distance(const double xyz[3], const double uvw[3], - bool coincident, double offset) { + bool coincident, double offset) +{ const double f = offset - xyz[i]; if (coincident or fabs(f) < FP_COINCIDENT or uvw[i] == 0.0) return INFTY; const double d = f / uvw[i]; @@ -184,7 +189,8 @@ axis_aligned_plane_distance(const double xyz[3], const double uvw[3], // The first template parameter indicates the axis normal to the plane. The // other two parameters indicate the other two axes. template void -axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { +axis_aligned_plane_normal(const double xyz[3], double uvw[3]) +{ uvw[i1] = 1.0; uvw[i2] = 0.0; uvw[i3] = 0.0; @@ -197,7 +203,8 @@ axis_aligned_plane_normal(const double xyz[3], double uvw[3]) { //! The plane is described by the equation \f$x - x_0 = 0\f$ //============================================================================== -class SurfaceXPlane : public Surface { +class SurfaceXPlane : public Surface +{ double x0; public: SurfaceXPlane(pugi::xml_node surf_node); @@ -207,20 +214,24 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) { +SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0); } -inline double SurfaceXPlane::evaluate(const double xyz[3]) const { +inline double SurfaceXPlane::evaluate(const double xyz[3]) const +{ return axis_aligned_plane_evaluate<0>(xyz, x0); } inline double SurfaceXPlane::distance(const double xyz[3], const double uvw[3], - bool coincident) const { + bool coincident) const +{ return axis_aligned_plane_distance<0>(xyz, uvw, coincident, x0); } -inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); } @@ -231,7 +242,8 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const { //! The plane is described by the equation \f$y - y_0 = 0\f$ //============================================================================== -class SurfaceYPlane : public Surface { +class SurfaceYPlane : public Surface +{ double y0; public: SurfaceYPlane(pugi::xml_node surf_node); @@ -241,20 +253,24 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) { +SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) +{ read_coeffs(surf_node, y0); } -inline double SurfaceYPlane::evaluate(const double xyz[3]) const { +inline double SurfaceYPlane::evaluate(const double xyz[3]) const +{ return axis_aligned_plane_evaluate<1>(xyz, y0); } inline double SurfaceYPlane::distance(const double xyz[3], const double uvw[3], - bool coincident) const { + bool coincident) const +{ return axis_aligned_plane_distance<1>(xyz, uvw, coincident, y0); } -inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); } @@ -265,7 +281,8 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const { //! The plane is described by the equation \f$z - z_0 = 0\f$ //============================================================================== -class SurfaceZPlane : public Surface { +class SurfaceZPlane : public Surface +{ double z0; public: SurfaceZPlane(pugi::xml_node surf_node); @@ -275,20 +292,24 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) { +SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) +{ read_coeffs(surf_node, z0); } -inline double SurfaceZPlane::evaluate(const double xyz[3]) const { +inline double SurfaceZPlane::evaluate(const double xyz[3]) const +{ return axis_aligned_plane_evaluate<2>(xyz, z0); } inline double SurfaceZPlane::distance(const double xyz[3], const double uvw[3], - bool coincident) const { + bool coincident) const +{ return axis_aligned_plane_distance<2>(xyz, uvw, coincident, z0); } -inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); } @@ -299,7 +320,8 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const { //! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ //============================================================================== -class SurfacePlane : public Surface { +class SurfacePlane : public Surface +{ double A, B, C, D; public: SurfacePlane(pugi::xml_node surf_node); @@ -309,18 +331,21 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfacePlane::SurfacePlane(pugi::xml_node surf_node) { +SurfacePlane::SurfacePlane(pugi::xml_node surf_node) +{ read_coeffs(surf_node, A, B, C, D); } double -SurfacePlane::evaluate(const double xyz[3]) const { +SurfacePlane::evaluate(const double xyz[3]) const +{ return A*xyz[0] + B*xyz[1] + C*xyz[2] - D; } double SurfacePlane::distance(const double xyz[3], const double uvw[3], - bool coincident) const { + bool coincident) const +{ const double f = A*xyz[0] + B*xyz[1] + C*xyz[2] - D; const double projection = A*uvw[0] + B*uvw[1] + C*uvw[2]; if (coincident or fabs(f) < FP_COINCIDENT or projection == 0.0) { @@ -333,7 +358,8 @@ SurfacePlane::distance(const double xyz[3], const double uvw[3], } void -SurfacePlane::normal(const double xyz[3], double uvw[3]) const { +SurfacePlane::normal(const double xyz[3], double uvw[3]) const +{ uvw[0] = A; uvw[1] = B; uvw[2] = C; @@ -348,7 +374,8 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const { // respectively. template double axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, - double offset2, double radius) { + double offset2, double radius) +{ const double xyz1 = xyz[i1] - offset1; const double xyz2 = xyz[i2] - offset2; return xyz1*xyz1 + xyz2*xyz2 - radius*radius; @@ -359,7 +386,8 @@ axis_aligned_cylinder_evaluate(const double xyz[3], double offset1, // should correspond with i2 and i3, respectively. template double axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], - bool coincident, double offset1, double offset2, double radius) { + bool coincident, double offset1, double offset2, double radius) +{ const double a = 1.0 - uvw[i1]*uvw[i1]; // u^2 + v^2 if (a == 0.0) return INFTY; @@ -404,7 +432,8 @@ axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], // should correspond with i2 and i3, respectively. template void axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, - double offset2) { + double offset2) +{ uvw[i2] = 2.0 * (xyz[i2] - offset1); uvw[i3] = 2.0 * (xyz[i3] - offset2); uvw[i1] = 0.0; @@ -418,7 +447,8 @@ axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, //! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceXCylinder : public Surface { +class SurfaceXCylinder : public Surface +{ double y0, z0, r; public: SurfaceXCylinder(pugi::xml_node surf_node); @@ -428,21 +458,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) { +SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) +{ read_coeffs(surf_node, y0, z0, r); } -inline double SurfaceXCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceXCylinder::evaluate(const double xyz[3]) const +{ return axis_aligned_cylinder_evaluate<1, 2>(xyz, y0, z0, r); } inline double SurfaceXCylinder::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cylinder_distance<0, 1, 2>(xyz, uvw, coincident, y0, z0, r); } -inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cylinder_normal<0, 1, 2>(xyz, uvw, y0, z0); } @@ -454,7 +488,8 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const { //! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceYCylinder : public Surface { +class SurfaceYCylinder : public Surface +{ double x0, z0, r; public: SurfaceYCylinder(pugi::xml_node surf_node); @@ -464,21 +499,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) { +SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, z0, r); } -inline double SurfaceYCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceYCylinder::evaluate(const double xyz[3]) const +{ return axis_aligned_cylinder_evaluate<0, 2>(xyz, x0, z0, r); } inline double SurfaceYCylinder::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cylinder_distance<1, 0, 2>(xyz, uvw, coincident, x0, z0, r); } -inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cylinder_normal<1, 0, 2>(xyz, uvw, x0, z0); } @@ -490,7 +529,8 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const { //! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceZCylinder : public Surface { +class SurfaceZCylinder : public Surface +{ double x0, y0, r; public: SurfaceZCylinder(pugi::xml_node surf_node); @@ -500,21 +540,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) { +SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, y0, r); } -inline double SurfaceZCylinder::evaluate(const double xyz[3]) const { +inline double SurfaceZCylinder::evaluate(const double xyz[3]) const +{ return axis_aligned_cylinder_evaluate<0, 1>(xyz, x0, y0, r); } inline double SurfaceZCylinder::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cylinder_distance<2, 0, 1>(xyz, uvw, coincident, x0, y0, r); } -inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); } @@ -526,7 +570,8 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const { //! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ //============================================================================== -class SurfaceSphere : public Surface { +class SurfaceSphere : public Surface +{ double x0, y0, z0, r; public: SurfaceSphere(pugi::xml_node surf_node); @@ -536,11 +581,13 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) { +SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, y0, z0, r); } -double SurfaceSphere::evaluate(const double xyz[3]) const { +double SurfaceSphere::evaluate(const double xyz[3]) const +{ const double x = xyz[0] - x0; const double y = xyz[1] - y0; const double z = xyz[2] - z0; @@ -548,7 +595,8 @@ double SurfaceSphere::evaluate(const double xyz[3]) const { } double SurfaceSphere::distance(const double xyz[3], const double uvw[3], - bool coincident) const { + bool coincident) const +{ const double x = xyz[0] - x0; const double y = xyz[1] - y0; const double z = xyz[2] - z0; @@ -585,7 +633,8 @@ double SurfaceSphere::distance(const double xyz[3], const double uvw[3], } } -inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const +{ uvw[0] = 2.0 * (xyz[0] - x0); uvw[1] = 2.0 * (xyz[1] - y0); uvw[2] = 2.0 * (xyz[2] - z0); @@ -600,7 +649,8 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const { // and offset3 should correspond with i1, i2, and i3, respectively. template double axis_aligned_cone_evaluate(const double xyz[3], double offset1, - double offset2, double offset3, double radius_sq) { + double offset2, double offset3, double radius_sq) +{ const double xyz1 = xyz[i1] - offset1; const double xyz2 = xyz[i2] - offset2; const double xyz3 = xyz[i3] - offset3; @@ -613,7 +663,8 @@ axis_aligned_cone_evaluate(const double xyz[3], double offset1, template double axis_aligned_cone_distance(const double xyz[3], const double uvw[3], bool coincident, double offset1, double offset2, double offset3, - double radius_sq) { + double radius_sq) +{ const double xyz1 = xyz[i1] - offset1; const double xyz2 = xyz[i2] - offset2; const double xyz3 = xyz[i3] - offset3; @@ -665,7 +716,8 @@ axis_aligned_cone_distance(const double xyz[3], const double uvw[3], // and offset3 should correspond with i1, i2, and i3, respectively. template void axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, - double offset2, double offset3, double radius_sq) { + double offset2, double offset3, double radius_sq) +{ uvw[i1] = -2.0 * radius_sq * (xyz[i1] - offset1); uvw[i2] = 2.0 * (xyz[i2] - offset2); uvw[i3] = 2.0 * (xyz[i3] - offset3); @@ -679,7 +731,8 @@ axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, //! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ //============================================================================== -class SurfaceXCone : public Surface { +class SurfaceXCone : public Surface +{ double x0, y0, z0, r_sq; public: SurfaceXCone(pugi::xml_node surf_node); @@ -689,21 +742,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) { +SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, y0, z0, r_sq); } -inline double SurfaceXCone::evaluate(const double xyz[3]) const { +inline double SurfaceXCone::evaluate(const double xyz[3]) const +{ return axis_aligned_cone_evaluate<0, 1, 2>(xyz, x0, y0, z0, r_sq); } inline double SurfaceXCone::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cone_distance<0, 1, 2>(xyz, uvw, coincident, x0, y0, z0, r_sq); } -inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cone_normal<0, 1, 2>(xyz, uvw, x0, y0, z0, r_sq); } @@ -715,7 +772,8 @@ inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const { //! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ //============================================================================== -class SurfaceYCone : public Surface { +class SurfaceYCone : public Surface +{ double x0, y0, z0, r_sq; public: SurfaceYCone(pugi::xml_node surf_node); @@ -725,21 +783,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) { +SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, y0, z0, r_sq); } -inline double SurfaceYCone::evaluate(const double xyz[3]) const { +inline double SurfaceYCone::evaluate(const double xyz[3]) const +{ return axis_aligned_cone_evaluate<1, 0, 2>(xyz, y0, x0, z0, r_sq); } inline double SurfaceYCone::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cone_distance<1, 0, 2>(xyz, uvw, coincident, y0, x0, z0, r_sq); } -inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cone_normal<1, 0, 2>(xyz, uvw, y0, x0, z0, r_sq); } @@ -751,7 +813,8 @@ inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const { //! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ //============================================================================== -class SurfaceZCone : public Surface { +class SurfaceZCone : public Surface +{ double x0, y0, z0, r_sq; public: SurfaceZCone(pugi::xml_node surf_node); @@ -761,21 +824,25 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) { +SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) +{ read_coeffs(surf_node, x0, y0, z0, r_sq); } -inline double SurfaceZCone::evaluate(const double xyz[3]) const { +inline double SurfaceZCone::evaluate(const double xyz[3]) const +{ return axis_aligned_cone_evaluate<2, 0, 1>(xyz, z0, x0, y0, r_sq); } inline double SurfaceZCone::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ return axis_aligned_cone_distance<2, 0, 1>(xyz, uvw, coincident, z0, x0, y0, r_sq); } -inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const { +inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const +{ axis_aligned_cone_normal<2, 0, 1>(xyz, uvw, z0, x0, y0, r_sq); } @@ -786,7 +853,8 @@ inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const { //! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ //============================================================================== -class SurfaceQuadric : public Surface { +class SurfaceQuadric : public Surface +{ // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 double A, B, C, D, E, F, G, H, J, K; public: @@ -797,12 +865,14 @@ public: void normal(const double xyz[3], double uvw[3]) const; }; -SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) { +SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) +{ read_coeffs(surf_node, A, B, C, D, E, F, G, H, J, K); } double -SurfaceQuadric::evaluate(const double xyz[3]) const { +SurfaceQuadric::evaluate(const double xyz[3]) const +{ const double &x = xyz[0]; const double &y = xyz[1]; const double &z = xyz[2]; @@ -813,7 +883,8 @@ SurfaceQuadric::evaluate(const double xyz[3]) const { double SurfaceQuadric::distance(const double xyz[3], - const double uvw[3], bool coincident) const { + const double uvw[3], bool coincident) const +{ const double &x = xyz[0]; const double &y = xyz[1]; const double &z = xyz[2]; @@ -866,7 +937,8 @@ SurfaceQuadric::distance(const double xyz[3], } void -SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const { +SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const +{ const double &x = xyz[0]; const double &y = xyz[1]; const double &z = xyz[2]; @@ -878,7 +950,8 @@ SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const { //============================================================================== extern "C" void -read_surfaces(pugi::xml_node *node) { +read_surfaces(pugi::xml_node *node) +{ // Count the number of surfaces. int n_surfaces = 0; for (pugi::xml_node surf_node = node->child("surface"); surf_node; @@ -952,16 +1025,19 @@ read_surfaces(pugi::xml_node *node) { //============================================================================== extern "C" bool -surface_sense(int surf_ind, double xyz[3], double uvw[3]) { +surface_sense(int surf_ind, double xyz[3], double uvw[3]) +{ return surfaces_c[surf_ind]->sense(xyz, uvw); } extern "C" double -surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) { +surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) +{ return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); } extern "C" void -surface_normal(int surf_ind, double xyz[3], double uvw[3]) { +surface_normal(int surf_ind, double xyz[3], double uvw[3]) +{ return surfaces_c[surf_ind]->normal(xyz, uvw); } From 163b6e3de5a7235e1152926880e5474ec44af8fb Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Wed, 11 Oct 2017 16:58:00 -0400 Subject: [PATCH 019/212] Remove Fortran code for surface distance and sense --- src/geometry.F90 | 67 ++--- src/surface_header.C | 2 +- src/surface_header.F90 | 560 +---------------------------------------- 3 files changed, 23 insertions(+), 606 deletions(-) diff --git a/src/geometry.F90 b/src/geometry.F90 index 8a449a284b..873582dec9 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -15,34 +15,34 @@ module geometry implicit none interface - function surface_sense_c(surf_ind, xyz, uvw) & + pure function surface_sense_c(surf_ind, xyz, uvw) & bind(C, name='surface_sense') result(sense) use ISO_C_BINDING implicit none - integer(C_INT), value :: surf_ind; - real(C_DOUBLE) :: xyz(3); - real(C_DOUBLE) :: uvw(3); - logical(C_BOOL) :: sense; + integer(C_INT), intent(in), value :: surf_ind; + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL) :: sense; end function surface_sense_c - function surface_distance_c(surf_ind, xyz, uvw, coincident) & + pure function surface_distance_c(surf_ind, xyz, uvw, coincident) & bind(C, name='surface_distance') result(d) use ISO_C_BINDING implicit none - integer(C_INT), value :: surf_ind; - real(C_DOUBLE) :: xyz(3); - real(C_DOUBLE) :: uvw(3); - logical(C_BOOL), value :: coincident; - real(C_DOUBLE) :: d; + integer(C_INT), intent(in), value :: surf_ind; + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL), intent(in), value :: coincident; + real(C_DOUBLE) :: d; end function surface_distance_c - subroutine surface_normal_c(surf_ind, xyz, uvw) & + pure subroutine surface_normal_c(surf_ind, xyz, uvw) & bind(C, name='surface_normal') use ISO_C_BINDING implicit none - integer(C_INT), value :: surf_ind; - real(C_DOUBLE) :: xyz(3); - real(C_DOUBLE) :: uvw(3); + integer(C_INT), intent(in), value :: surf_ind; + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(out) :: uvw(3); end subroutine surface_normal_c end interface @@ -62,8 +62,7 @@ contains ! expression using a stack, similar to how a RPN calculator would work. !=============================================================================== - !pure function cell_contains(c, p) result(in_cell) - function cell_contains(c, p) result(in_cell) + pure function cell_contains(c, p) result(in_cell) type(Cell), intent(in) :: c type(Particle), intent(in) :: p logical :: in_cell @@ -75,8 +74,7 @@ contains end if end function cell_contains - !pure function simple_cell_contains(c, p) result(in_cell) - function simple_cell_contains(c, p) result(in_cell) + pure function simple_cell_contains(c, p) result(in_cell) type(Cell), intent(in) :: c type(Particle), intent(in) :: p logical :: in_cell @@ -84,8 +82,6 @@ contains integer :: i integer :: token logical :: actual_sense ! sense of particle wrt surface - logical :: alt_sense - real(8) :: uvw1(3), uvw2(3) in_cell = .true. do i = 1, size(c%rpn) @@ -101,25 +97,8 @@ contains in_cell = .false. exit else - actual_sense = surfaces(abs(token))%obj%sense(& + actual_sense = surface_sense_c(abs(token)-1, & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) - alt_sense = surface_sense_c(abs(token)-1, & - p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) - if (actual_sense .neqv. alt_sense) then - write(*, *) surfaces(abs(token)) % obj % id - write(*, *) p % coord (p % n_coord) % xyz - write(*, *) p % coord (p % n_coord) % uvw - write(*, *) actual_sense, alt_sense - call fatal_error("") - end if - uvw1 = surfaces(abs(token))%obj%normal(p%coord(p%n_coord)%xyz) - call surface_normal_c(abs(token)-1, p%coord(p%n_coord)%xyz, uvw2) - if (.not. all(uvw1 - uvw2 == ZERO)) then - write(*, *) "Surface normals don't match" - write(*, *) uvw1 - write(*, *) uvw2 - call fatal_error("") - end if if (actual_sense .neqv. (token > 0)) then in_cell = .false. exit @@ -167,7 +146,7 @@ contains elseif (-token == p%surface) then stack(i_stack) = .false. else - actual_sense = surfaces(abs(token))%obj%sense(& + actual_sense = surface_sense_c(abs(token)-1, & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) stack(i_stack) = (actual_sense .eqv. (token > 0)) end if @@ -539,7 +518,6 @@ contains type(Cell), pointer :: c class(Surface), pointer :: surf class(Lattice), pointer :: lat - real(8) :: d_alt ! inialize distance to infinity (huge) dist = INFINITY @@ -573,13 +551,8 @@ contains if (index_surf >= OP_UNION) cycle ! Calculate distance to surface - surf => surfaces(index_surf) % obj - d = surf % distance(p % coord(j) % xyz, p % coord(j) % uvw, coincident) - d_alt = surface_distance_c(index_surf-1, p % coord(j) % xyz, & + d = surface_distance_c(index_surf-1, p % coord(j) % xyz, & p % coord(j) % uvw, logical(coincident, kind=C_BOOL)) - if (d /= d_alt) then - write(*, *) d, d_alt - end if ! Check if calculated distance is new minimum if (d < d_surf) then diff --git a/src/surface_header.C b/src/surface_header.C index 6992c2e2ac..cf200e5e46 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -33,7 +33,7 @@ const char* get_coeff_str(pugi::xml_node surf_node) return surf_node.child_value("coeffs"); } else { std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - return NULL; + return nullptr; } } diff --git a/src/surface_header.F90 b/src/surface_header.F90 index ed4ef86e09..b0da37c1e0 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -21,10 +21,8 @@ module surface_header integer :: i_periodic = NONE ! Index of corresponding periodic surface character(len=104) :: name = "" ! User-defined name contains - procedure :: sense procedure :: reflect procedure(surface_evaluate_), deferred :: evaluate - procedure(surface_distance_), deferred :: distance procedure(surface_normal_), deferred :: normal end type Surface @@ -36,15 +34,6 @@ module surface_header real(8) :: f end function surface_evaluate_ - 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 surface_distance_ - pure function surface_normal_(this, xyz) result(uvw) import Surface class(Surface), intent(in) :: this @@ -63,8 +52,8 @@ module surface_header !=============================================================================== ! All the derived types below are extensions of the abstract Surface type. They -! inherent the reflect() and sense() type-bound procedures and must implement -! evaluate(), distance(), and normal() +! inherent the reflect() type-bound procedure and must implement evaluate(), +! and normal() !=============================================================================== type, extends(Surface) :: SurfaceXPlane @@ -72,7 +61,6 @@ module surface_header real(8) :: x0 contains procedure :: evaluate => x_plane_evaluate - procedure :: distance => x_plane_distance procedure :: normal => x_plane_normal end type SurfaceXPlane @@ -81,7 +69,6 @@ module surface_header real(8) :: y0 contains procedure :: evaluate => y_plane_evaluate - procedure :: distance => y_plane_distance procedure :: normal => y_plane_normal end type SurfaceYPlane @@ -90,7 +77,6 @@ module surface_header real(8) :: z0 contains procedure :: evaluate => z_plane_evaluate - procedure :: distance => z_plane_distance procedure :: normal => z_plane_normal end type SurfaceZPlane @@ -102,7 +88,6 @@ module surface_header real(8) :: D contains procedure :: evaluate => plane_evaluate - procedure :: distance => plane_distance procedure :: normal => plane_normal end type SurfacePlane @@ -113,7 +98,6 @@ module surface_header real(8) :: r contains procedure :: evaluate => x_cylinder_evaluate - procedure :: distance => x_cylinder_distance procedure :: normal => x_cylinder_normal end type SurfaceXCylinder @@ -124,7 +108,6 @@ module surface_header real(8) :: r contains procedure :: evaluate => y_cylinder_evaluate - procedure :: distance => y_cylinder_distance procedure :: normal => y_cylinder_normal end type SurfaceYCylinder @@ -135,7 +118,6 @@ module surface_header real(8) :: r contains procedure :: evaluate => z_cylinder_evaluate - procedure :: distance => z_cylinder_distance procedure :: normal => z_cylinder_normal end type SurfaceZCylinder @@ -147,7 +129,6 @@ module surface_header real(8) :: r contains procedure :: evaluate => sphere_evaluate - procedure :: distance => sphere_distance procedure :: normal => sphere_normal end type SurfaceSphere @@ -159,7 +140,6 @@ module surface_header real(8) :: r2 contains procedure :: evaluate => x_cone_evaluate - procedure :: distance => x_cone_distance procedure :: normal => x_cone_normal end type SurfaceXCone @@ -171,7 +151,6 @@ module surface_header real(8) :: r2 contains procedure :: evaluate => y_cone_evaluate - procedure :: distance => y_cone_distance procedure :: normal => y_cone_normal end type SurfaceYCone @@ -183,7 +162,6 @@ module surface_header real(8) :: r2 contains procedure :: evaluate => z_cone_evaluate - procedure :: distance => z_cone_distance procedure :: normal => z_cone_normal end type SurfaceZCone @@ -192,7 +170,6 @@ module surface_header real(8) :: A, B, C, D, E, F, G, H, J, K contains procedure :: evaluate => quadric_evaluate - procedure :: distance => quadric_distance procedure :: normal => quadric_normal end type SurfaceQuadric @@ -205,36 +182,6 @@ module surface_header contains -!=============================================================================== -! SENSE determines whether a point is on the 'positive' or 'negative' side of a -! surface. This routine is crucial for determining what cell a particular point -! is in. The positive side is indicated by a returned value of .true. and the -! negative side is indicated by a returned value of .false. -!=============================================================================== - - pure function sense(this, xyz, uvw) result(s) - class(Surface), intent(in) :: this ! surface - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical :: s ! sense of particle - - real(8) :: f ! surface function evaluated at point - - ! Evaluate the surface equation at the particle's coordinates to determine - ! which side the particle is on - f = this%evaluate(xyz) - - ! Check which side of surface the point is on - if (abs(f) < FP_COINCIDENT) then - ! Particle may be coincident with this surface. To determine the sense, we - ! look at the direction of the particle relative to the surface normal (by - ! default in the positive direction) via their dot product. - s = (dot_product(uvw, this%normal(xyz)) > ZERO) - else - s = (f > ZERO) - end if - end function sense - !=============================================================================== ! REFLECT determines the direction a particle will travel if it is specularly ! reflected from the surface at a given position and direction. The position is @@ -275,24 +222,6 @@ contains f = xyz(1) - this%x0 end function x_plane_evaluate - pure function x_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%x0 - xyz(1) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(1) == ZERO) then - d = INFINITY - else - d = f/uvw(1) - if (d < ZERO) d = INFINITY - end if - end function x_plane_distance - pure function x_plane_normal(this, xyz) result(uvw) class(SurfaceXPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -313,24 +242,6 @@ contains f = xyz(2) - this%y0 end function y_plane_evaluate - pure function y_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%y0 - xyz(2) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(2) == ZERO) then - d = INFINITY - else - d = f/uvw(2) - if (d < ZERO) d = INFINITY - end if - end function y_plane_distance - pure function y_plane_normal(this, xyz) result(uvw) class(SurfaceYPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -353,24 +264,6 @@ contains end function z_plane_evaluate - pure function z_plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - - f = this%z0 - xyz(3) - if (coincident .or. abs(f) < FP_COINCIDENT .or. uvw(3) == ZERO) then - d = INFINITY - else - d = f/uvw(3) - if (d < ZERO) d = INFINITY - end if - end function z_plane_distance - pure function z_plane_normal(this, xyz) result(uvw) class(SurfaceZPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -391,26 +284,6 @@ contains f = this%A*xyz(1) + this%B*xyz(2) + this%C*xyz(3) - this%D end function plane_evaluate - pure function plane_distance(this, xyz, uvw, coincident) result(d) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: f - real(8) :: projection - - f = this%A*xyz(1) + this%B*xyz(2) + this%C*xyz(3) - this%D - projection = this%A*uvw(1) + this%B*uvw(2) + this%C*uvw(3) - if (coincident .or. abs(f) < FP_COINCIDENT .or. projection == ZERO) then - d = INFINITY - else - d = -f/projection - if (d < ZERO) d = INFINITY - end if - end function plane_distance - pure function plane_normal(this, xyz) result(uvw) class(SurfacePlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -435,60 +308,6 @@ contains f = y*y + z*z - this%r*this%r end function x_cylinder_evaluate - pure function x_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: y, z, k, a, c, quad - - a = ONE - uvw(1)*uvw(1) ! v^2 + w^2 - if (a == ZERO) then - d = INFINITY - else - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - k = y*uvw(2) + z*uvw(3) - c = y*y + z*z - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function x_cylinder_distance - pure function x_cylinder_normal(this, xyz) result(uvw) class(SurfaceXCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -515,60 +334,6 @@ contains f = x*x + z*z - this%r*this%r end function y_cylinder_evaluate - pure function y_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, z, k, a, c, quad - - a = ONE - uvw(2)*uvw(2) ! u^2 + w^2 - if (a == ZERO) then - d = INFINITY - else - x = xyz(1) - this%x0 - z = xyz(3) - this%z0 - k = x*uvw(1) + z*uvw(3) - c = x*x + z*z - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function y_cylinder_distance - pure function y_cylinder_normal(this, xyz) result(uvw) class(SurfaceYCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -595,60 +360,6 @@ contains f = x*x + y*y - this%r*this%r end function z_cylinder_evaluate - pure function z_cylinder_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, k, a, c, quad - - a = ONE - uvw(3)*uvw(3) ! u^2 + v^2 - if (a == ZERO) then - d = INFINITY - else - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - k = x*uvw(1) + y*uvw(2) - c = x*x + y*y - this%r*this%r - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cylinder - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cylinder, thus one distance is positive/negative - ! and the other is zero. The sign of k determines if we are facing in or - ! out - - if (k >= ZERO) then - d = INFINITY - else - d = (-k + sqrt(quad))/a - end if - - elseif (c < ZERO) then - ! particle is inside the cylinder, thus one distance must be negative - ! and one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = (-k + sqrt(quad))/a - - else - ! particle is outside the cylinder, thus both distances are either - ! positive or negative. If positive, the smaller distance is the one - ! with positive sign on sqrt(quad) - - d = (-k - sqrt(quad))/a - if (d < ZERO) d = INFINITY - - end if - end if - end function z_cylinder_distance - pure function z_cylinder_normal(this, xyz) result(uvw) class(SurfaceZCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -676,55 +387,6 @@ contains f = x*x + y*y + z*z - this%r*this%r end function sphere_evaluate - pure function sphere_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - k = x*uvw(1) + y*uvw(2) + z*uvw(3) - c = x*x + y*y + z*z - this%r*this%r - quad = k*k - c - - if (quad < ZERO) then - ! no intersection with sphere - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the sphere, thus one distance is positive/negative and - ! the other is zero. The sign of k determines if we are facing in or out - - if (k >= ZERO) then - d = INFINITY - else - d = -k + sqrt(quad) - end if - - elseif (c < ZERO) then - ! particle is inside the sphere, thus one distance must be negative and - ! one must be positive. The positive distance will be the one with - ! negative sign on sqrt(quad) - - d = -k + sqrt(quad) - - else - ! particle is outside the sphere, thus both distances are either positive - ! or negative. If positive, the smaller distance is the one with positive - ! sign on sqrt(quad) - - d = -k - sqrt(quad) - if (d < ZERO) d = INFINITY - - end if - end function sphere_distance - pure function sphere_normal(this, xyz) result(uvw) class(SurfaceSphere), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -750,59 +412,6 @@ contains f = y*y + z*z - this%r2*x*x end function x_cone_evaluate - pure function x_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(2)*uvw(2) + uvw(3)*uvw(3) - this%r2*uvw(1)*uvw(1) - k = y*uvw(2) + z*uvw(3) - this%r2*x*uvw(1) - c = y*y + z*z - this%r2*x*x - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function x_cone_distance - pure function x_cone_normal(this, xyz) result(uvw) class(SurfaceXCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -830,59 +439,6 @@ contains f = x*x + z*z - this%r2*y*y end function y_cone_evaluate - pure function y_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(1)*uvw(1) + uvw(3)*uvw(3) - this%r2*uvw(2)*uvw(2) - k = x*uvw(1) + z*uvw(3) - this%r2*y*uvw(2) - c = x*x + z*z - this%r2*y*y - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function y_cone_distance - pure function y_cone_normal(this, xyz) result(uvw) class(SurfaceYCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -910,59 +466,6 @@ contains f = x*x + y*y - this%r2*z*z end function z_cone_evaluate - pure function z_cone_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: x, y, z, k, a, b, c, quad - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - a = uvw(1)*uvw(1) + uvw(2)*uvw(2) - this%r2*uvw(3)*uvw(3) - k = x*uvw(1) + y*uvw(2) - this%r2*z*uvw(3) - c = x*x + y*y - this%r2*z*z - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with cone - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the cone, thus one distance is positive/negative and the - ! other is zero. The sign of k determines which distance is zero and which - ! is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end function z_cone_distance - pure function z_cone_normal(this, xyz) result(uvw) class(SurfaceZCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -989,65 +492,6 @@ contains end associate end function quadric_evaluate - pure function quadric_distance(this, xyz, uvw, coincident) result(d) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(in) :: uvw(3) - logical, intent(in) :: coincident - real(8) :: d - - real(8) :: a, k, c - real(8) :: quad, b - - associate (x => xyz(1), y => xyz(2), z => xyz(3), & - u => uvw(1), v => uvw(2), w => uvw(3)) - - a = this%A*u*u + this%B*v*v + this%C*w*w + this%D*u*v + this%E*v*w + & - this%F*u*w - k = (this%A*u*x + this%B*v*y + this%C*w*z + HALF*(this%D*(u*y + v*x) + & - this%E*(v*z + w*y) + this%F*(w*x + u*z) + this%G*u + this%H*v + & - this%J*w)) - c = this%A*x*x + this%B*y*y + this%C*z*z + this%D*x*y + this%E*y*z + & - this%F*x*z + this%G*x + this%H*y + this%J*z + this%K - quad = k*k - a*c - - if (quad < ZERO) then - ! no intersection with surface - - d = INFINITY - - elseif (coincident .or. abs(c) < FP_COINCIDENT) then - ! particle is on the surface, thus one distance is positive/negative and - ! the other is zero. The sign of k determines which distance is zero and - ! which is not. - - if (k >= ZERO) then - d = (-k - sqrt(quad))/a - else - d = (-k + sqrt(quad))/a - end if - - else - ! calculate both solutions to the quadratic - quad = sqrt(quad) - d = (-k - quad)/a - b = (-k + quad)/a - - ! determine the smallest positive solution - if (d < ZERO) then - if (b > ZERO) then - d = b - end if - else - if (b > ZERO) d = min(d, b) - end if - end if - - ! If the distance was negative, set boundary distance to infinity - if (d <= ZERO) d = INFINITY - end associate - end function quadric_distance - pure function quadric_normal(this, xyz) result(uvw) class(SurfaceQuadric), intent(in) :: this real(8), intent(in) :: xyz(3) From 38aa76c9dc9cdab0c10f35c2355d20f9842b65bc Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 19 Jan 2018 00:54:39 -0500 Subject: [PATCH 020/212] Implement C++ periodic BCs --- src/geometry.F90 | 11 +++ src/surface_header.C | 136 +++++++++++++++++++++++++++++++++-- src/surface_header.F90 | 157 +---------------------------------------- src/tracking.F90 | 63 +---------------- 4 files changed, 145 insertions(+), 222 deletions(-) diff --git a/src/geometry.F90 b/src/geometry.F90 index 873582dec9..a0a19f1bfc 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -44,6 +44,17 @@ module geometry real(C_DOUBLE), intent(in) :: xyz(3); real(C_DOUBLE), intent(out) :: uvw(3); end subroutine surface_normal_c + + function surface_periodic_c(surf_ind1, surf_ind2, xyz, uvw) & + bind(C, name="surface_periodic") result(rotational) + use ISO_C_BINDING + implicit none + integer(C_INT), intent(in), value :: surf_ind1; + integer(C_INT), intent(in), value :: surf_ind2; + real(C_DOUBLE), intent(inout) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + logical(C_BOOL) :: rotational + end function surface_periodic_c end interface contains diff --git a/src/surface_header.C b/src/surface_header.C index cf200e5e46..23fe5adb35 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -5,6 +5,7 @@ #include "pugixml/pugixml.hpp" // DEBUGGING +#include #include //============================================================================== @@ -89,14 +90,14 @@ public: neighbor_neg[]; //!< List of cells on negative side int bc; //!< Boundary condition //TODO: switch that zero to a NONE constant. - int i_periodic = 0; //!< Index of corresponding periodic surface + //int i_periodic = 0; //!< Index of corresponding periodic surface char name[104]; //!< User-defined name //! Determine which side of a surface a point lies on. //! @param xyz[3] The 3D Cartesian coordinate of a point. //! @param uvw[3] A direction used to "break ties" and pick a sense when the //! point is very close to the surface. - //! @return True if the point is on the "positive" side of the surface and + //! @return true if the point is on the "positive" side of the surface and //! false otherwise. bool sense(const double xyz[3], const double uvw[3]) const; @@ -163,6 +164,29 @@ Surface::reflect(const double xyz[3], double uvw[3]) const uvw[2] -= 2.0 * projection / magnitude * norm[2]; } +//============================================================================== +//! A `Surface` that supports periodic boundary conditions. +//! +//! Translational periodicity is supported for the `XPlane`, `YPlane`, `ZPlane`, +//! and `Plane` types. Rotational periodicity is supported for +//! `XPlane`-`YPlane` pairs. +//============================================================================== + +class PeriodicSurface : public Surface +{ +public: + //! Translate a particle onto this surface from a periodic partner surface. + //! @param other A pointer to the partner surface in this periodic BC. + //! @param xyz[3] A point on the partner surface that will be translated onto + //! this surface. + //! @param uvw[3] A direction that will be rotated for systems with rotational + //! periodicity. + //! @return true if this surface and its partner make a rotationally-periodic + //! boundary condition. + virtual bool periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const = 0; +}; + //============================================================================== // Generic functions for x-, y-, and z-, planes. //============================================================================== @@ -203,7 +227,7 @@ axis_aligned_plane_normal(const double xyz[3], double uvw[3]) //! The plane is described by the equation \f$x - x_0 = 0\f$ //============================================================================== -class SurfaceXPlane : public Surface +class SurfaceXPlane : public PeriodicSurface { double x0; public: @@ -212,6 +236,8 @@ public: double distance(const double xyz[3], const double uvw[3], const bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; }; SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) @@ -235,6 +261,32 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); } +bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + double other_norm[3]; + other->normal(xyz, other_norm); + if (other_norm[0] == 1 and other_norm[1] == 0 and other_norm[2] == 0) { + xyz[0] = x0; + return false; + } else { + // Assume the partner is an YPlane (the only supported partner). Use the + // evaluate function to find y0, then adjust xyz and uvw for rotational + // symmetry. + double xyz_test[3] {0, 0, 0}; + double y0 = -other->evaluate(xyz_test); + xyz[1] = xyz[0] - x0 + y0; + xyz[0] = x0; + xyz[2] = xyz[2]; + + double u = uvw[0]; + uvw[0] = -uvw[1]; + uvw[1] = u; + + return true; + } +}; + //============================================================================== // SurfaceYPlane //! A plane perpendicular to the y-axis. @@ -242,7 +294,7 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const //! The plane is described by the equation \f$y - y_0 = 0\f$ //============================================================================== -class SurfaceYPlane : public Surface +class SurfaceYPlane : public PeriodicSurface { double y0; public: @@ -251,6 +303,8 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; }; SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) @@ -274,6 +328,32 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); } +bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + double other_norm[3]; + other->normal(xyz, other_norm); + if (other_norm[0] == 0 and other_norm[1] == 1 and other_norm[2] == 0) { + // The periodic partner is also aligned along y. Just change the y coord. + xyz[1] = y0; + return false; + } else { + // Assume the partner is an XPlane (the only supported partner). Use the + // evaluate function to find x0, then adjust xyz and uvw for rotational + // symmetry. + double xyz_test[3] {0, 0, 0}; + double x0 = -other->evaluate(xyz_test); + xyz[0] = xyz[1] - y0 + x0; + xyz[1] = y0; + + double u = uvw[0]; + uvw[0] = uvw[1]; + uvw[1] = -u; + + return true; + } +}; + //============================================================================== // SurfaceZPlane //! A plane perpendicular to the z-axis. @@ -281,7 +361,7 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const //! The plane is described by the equation \f$z - z_0 = 0\f$ //============================================================================== -class SurfaceZPlane : public Surface +class SurfaceZPlane : public PeriodicSurface { double z0; public: @@ -290,6 +370,8 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; }; SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) @@ -313,6 +395,14 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); } +bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + // Assume the other plane is aligned along z. Just change the z coord. + xyz[2] = z0; + return false; +}; + //============================================================================== // SurfacePlane //! A general plane. @@ -320,7 +410,7 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const //! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ //============================================================================== -class SurfacePlane : public Surface +class SurfacePlane : public PeriodicSurface { double A, B, C, D; public: @@ -329,6 +419,8 @@ public: double distance(const double xyz[3], const double uvw[3], const bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; }; SurfacePlane::SurfacePlane(pugi::xml_node surf_node) @@ -365,6 +457,22 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const uvw[2] = C; } +bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const +{ + // This function assumes the other plane shares this plane's normal direction. + + // Determine the distance to intersection. + double d = evaluate(xyz) / (A*A + B*B + C*C); + + // Move the particle that distance along the normal vector. + xyz[0] -= d * A; + xyz[1] -= d * B; + xyz[2] -= d * C; + + return false; +} + //============================================================================== // Generic functions for x-, y-, and z-, cylinders //============================================================================== @@ -1041,3 +1149,19 @@ surface_normal(int surf_ind, double xyz[3], double uvw[3]) { return surfaces_c[surf_ind]->normal(xyz, uvw); } + +extern "C" bool +surface_periodic(int surf_ind1, int surf_ind2, double xyz[3], double uvw[3]) +{ + // Hopefully this function has only been called on a pair of surfaces that + // support periodic BCs (checking should have been done when reading the + // geometry XML). Downcast the surfaces to the PeriodicSurface type so we + // can call the periodic_translate method. + Surface *surf1_gen = surfaces_c[surf_ind1]; + PeriodicSurface *surf1 = dynamic_cast(surf1_gen); + Surface *surf2_gen = surfaces_c[surf_ind2]; + PeriodicSurface *surf2 = dynamic_cast(surf2_gen); + + // Call the type-bound methods. + return surf2->periodic_translate(surf1, xyz, uvw); +} diff --git a/src/surface_header.F90 b/src/surface_header.F90 index b0da37c1e0..d9a00170ba 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -22,18 +22,10 @@ module surface_header character(len=104) :: name = "" ! User-defined name contains procedure :: reflect - procedure(surface_evaluate_), deferred :: evaluate procedure(surface_normal_), deferred :: normal end type Surface abstract interface - 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 surface_evaluate_ - pure function surface_normal_(this, xyz) result(uvw) import Surface class(Surface), intent(in) :: this @@ -52,15 +44,13 @@ module surface_header !=============================================================================== ! All the derived types below are extensions of the abstract Surface type. They -! inherent the reflect() type-bound procedure and must implement evaluate(), -! and normal() +! inherent the reflect() type-bound procedure and must implement normal() !=============================================================================== type, extends(Surface) :: SurfaceXPlane ! x = x0 real(8) :: x0 contains - procedure :: evaluate => x_plane_evaluate procedure :: normal => x_plane_normal end type SurfaceXPlane @@ -68,7 +58,6 @@ module surface_header ! y = y0 real(8) :: y0 contains - procedure :: evaluate => y_plane_evaluate procedure :: normal => y_plane_normal end type SurfaceYPlane @@ -76,7 +65,6 @@ module surface_header ! z = z0 real(8) :: z0 contains - procedure :: evaluate => z_plane_evaluate procedure :: normal => z_plane_normal end type SurfaceZPlane @@ -87,7 +75,6 @@ module surface_header real(8) :: C real(8) :: D contains - procedure :: evaluate => plane_evaluate procedure :: normal => plane_normal end type SurfacePlane @@ -97,7 +84,6 @@ module surface_header real(8) :: z0 real(8) :: r contains - procedure :: evaluate => x_cylinder_evaluate procedure :: normal => x_cylinder_normal end type SurfaceXCylinder @@ -107,7 +93,6 @@ module surface_header real(8) :: z0 real(8) :: r contains - procedure :: evaluate => y_cylinder_evaluate procedure :: normal => y_cylinder_normal end type SurfaceYCylinder @@ -117,7 +102,6 @@ module surface_header real(8) :: y0 real(8) :: r contains - procedure :: evaluate => z_cylinder_evaluate procedure :: normal => z_cylinder_normal end type SurfaceZCylinder @@ -128,7 +112,6 @@ module surface_header real(8) :: z0 real(8) :: r contains - procedure :: evaluate => sphere_evaluate procedure :: normal => sphere_normal end type SurfaceSphere @@ -139,7 +122,6 @@ module surface_header real(8) :: z0 real(8) :: r2 contains - procedure :: evaluate => x_cone_evaluate procedure :: normal => x_cone_normal end type SurfaceXCone @@ -150,7 +132,6 @@ module surface_header real(8) :: z0 real(8) :: r2 contains - procedure :: evaluate => y_cone_evaluate procedure :: normal => y_cone_normal end type SurfaceYCone @@ -161,7 +142,6 @@ module surface_header real(8) :: z0 real(8) :: r2 contains - procedure :: evaluate => z_cone_evaluate procedure :: normal => z_cone_normal end type SurfaceZCone @@ -169,7 +149,6 @@ module surface_header ! Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 real(8) :: A, B, C, D, E, F, G, H, J, K contains - procedure :: evaluate => quadric_evaluate procedure :: normal => quadric_normal end type SurfaceQuadric @@ -214,14 +193,6 @@ contains ! SurfaceXPlane Implementation !=============================================================================== - pure function x_plane_evaluate(this, xyz) result(f) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(1) - this%x0 - end function x_plane_evaluate - pure function x_plane_normal(this, xyz) result(uvw) class(SurfaceXPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -234,14 +205,6 @@ contains ! SurfaceYPlane Implementation !=============================================================================== - pure function y_plane_evaluate(this, xyz) result(f) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(2) - this%y0 - end function y_plane_evaluate - pure function y_plane_normal(this, xyz) result(uvw) class(SurfaceYPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -254,16 +217,6 @@ contains ! SurfaceZPlane Implementation !=============================================================================== - pure function z_plane_evaluate(this, xyz) result(f) - - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = xyz(3) - this%z0 - - end function z_plane_evaluate - pure function z_plane_normal(this, xyz) result(uvw) class(SurfaceZPlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -276,14 +229,6 @@ contains ! SurfacePlane Implementation !=============================================================================== - pure function plane_evaluate(this, xyz) result(f) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - f = this%A*xyz(1) + this%B*xyz(2) + this%C*xyz(3) - this%D - end function plane_evaluate - pure function plane_normal(this, xyz) result(uvw) class(SurfacePlane), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -296,18 +241,6 @@ contains ! SurfaceXCylinder Implementation !=============================================================================== - pure function x_cylinder_evaluate(this, xyz) result(f) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: y, z - - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = y*y + z*z - this%r*this%r - end function x_cylinder_evaluate - pure function x_cylinder_normal(this, xyz) result(uvw) class(SurfaceXCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -322,18 +255,6 @@ contains ! SurfaceYCylinder Implementation !=============================================================================== - pure function y_cylinder_evaluate(this, xyz) result(f) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, z - - x = xyz(1) - this%x0 - z = xyz(3) - this%z0 - f = x*x + z*z - this%r*this%r - end function y_cylinder_evaluate - pure function y_cylinder_normal(this, xyz) result(uvw) class(SurfaceYCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -348,18 +269,6 @@ contains ! SurfaceZCylinder Implementation !=============================================================================== - pure function z_cylinder_evaluate(this, xyz) result(f) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - f = x*x + y*y - this%r*this%r - end function z_cylinder_evaluate - pure function z_cylinder_normal(this, xyz) result(uvw) class(SurfaceZCylinder), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -374,19 +283,6 @@ contains ! SurfaceSphere Implementation !=============================================================================== - pure function sphere_evaluate(this, xyz) result(f) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + y*y + z*z - this%r*this%r - end function sphere_evaluate - pure function sphere_normal(this, xyz) result(uvw) class(SurfaceSphere), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -399,19 +295,6 @@ contains ! SurfaceXCone Implementation !=============================================================================== - pure function x_cone_evaluate(this, xyz) result(f) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = y*y + z*z - this%r2*x*x - end function x_cone_evaluate - pure function x_cone_normal(this, xyz) result(uvw) class(SurfaceXCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -426,19 +309,6 @@ contains ! SurfaceYCone Implementation !=============================================================================== - pure function y_cone_evaluate(this, xyz) result(f) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + z*z - this%r2*y*y - end function y_cone_evaluate - pure function y_cone_normal(this, xyz) result(uvw) class(SurfaceYCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -453,19 +323,6 @@ contains ! SurfaceZCone Implementation !=============================================================================== - pure function z_cone_evaluate(this, xyz) result(f) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - real(8) :: x, y, z - - x = xyz(1) - this%x0 - y = xyz(2) - this%y0 - z = xyz(3) - this%z0 - f = x*x + y*y - this%r2*z*z - end function z_cone_evaluate - pure function z_cone_normal(this, xyz) result(uvw) class(SurfaceZCone), intent(in) :: this real(8), intent(in) :: xyz(3) @@ -480,18 +337,6 @@ contains ! SurfaceQuadric Implementation !=============================================================================== - pure function quadric_evaluate(this, xyz) result(f) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: f - - associate (x => xyz(1), y => xyz(2), z => xyz(3)) - f = x*(this%A*x + this%D*y + this%G) + & - y*(this%B*y + this%E*z + this%H) + & - z*(this%C*z + this%F*x + this%J) + this%K - end associate - end function quadric_evaluate - pure function quadric_normal(this, xyz) result(uvw) class(SurfaceQuadric), intent(in) :: this real(8), intent(in) :: xyz(3) diff --git a/src/tracking.F90 b/src/tracking.F90 index 65769a7f18..4f0f110bc7 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -5,7 +5,7 @@ module tracking use error, only: fatal_error, warning, write_message use geometry_header, only: cells use geometry, only: find_cell, distance_to_boundary, cross_lattice, & - check_cell_overlap + check_cell_overlap, surface_periodic_c use message_passing use mgxs_header use nuclide_header @@ -290,7 +290,6 @@ contains real(8) :: v ! y-component of direction real(8) :: w ! z-component of direction real(8) :: norm ! "norm" of surface normal - real(8) :: d ! distance between point and plane real(8) :: xyz(3) ! Saved global coordinate integer :: i_surface ! index in surfaces logical :: rotational ! if rotational periodic BC applied @@ -412,64 +411,8 @@ contains p % coord(1) % xyz = xyz end if - rotational = .false. - select type (surf) - type is (SurfaceXPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceXPlane) - p % coord(1) % xyz(1) = opposite % x0 - type is (SurfaceYPlane) - rotational = .true. - - ! Rotate direction - u = p % coord(1) % uvw(1) - v = p % coord(1) % uvw(2) - p % coord(1) % uvw(1) = v - p % coord(1) % uvw(2) = -u - - ! Rotate position - p % coord(1) % xyz(1) = surf % x0 + p % coord(1) % xyz(2) - opposite % y0 - p % coord(1) % xyz(2) = opposite % y0 - end select - - type is (SurfaceYPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceYPlane) - p % coord(1) % xyz(2) = opposite % y0 - type is (SurfaceXPlane) - rotational = .true. - - ! Rotate direction - u = p % coord(1) % uvw(1) - v = p % coord(1) % uvw(2) - p % coord(1) % uvw(1) = -v - p % coord(1) % uvw(2) = u - - ! Rotate position - p % coord(1) % xyz(2) = surf % y0 + p % coord(1) % xyz(1) - opposite % x0 - p % coord(1) % xyz(1) = opposite % x0 - end select - - type is (SurfaceZPlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfaceZPlane) - p % coord(1) % xyz(3) = opposite % z0 - end select - - type is (SurfacePlane) - select type (opposite => surfaces(surf % i_periodic) % obj) - type is (SurfacePlane) - ! Get surface normal for opposite plane - xyz(:) = opposite % normal(p % coord(1) % xyz) - - ! Determine distance to plane - norm = xyz(1)*xyz(1) + xyz(2)*xyz(2) + xyz(3)*xyz(3) - d = opposite % evaluate(p % coord(1) % xyz) / norm - - ! Move particle along normal vector based on distance - p % coord(1) % xyz(:) = p % coord(1) % xyz(:) - d*xyz - end select - end select + rotational = surface_periodic_c(i_surface-1, surf % i_periodic-1, & + p % coord(1) % xyz, p % coord(1) % uvw) ! Reassign particle's surface if (rotational) then From 7af296902bbb9ae7b0409eafb5060feacfb1d2ec Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 19 Jan 2018 01:27:04 -0500 Subject: [PATCH 021/212] Remove Fortran surface reflection code --- src/geometry.F90 | 15 ++- src/surface_header.C | 14 ++- src/surface_header.F90 | 226 +---------------------------------------- src/tracking.F90 | 5 +- 4 files changed, 26 insertions(+), 234 deletions(-) diff --git a/src/geometry.F90 b/src/geometry.F90 index a0a19f1bfc..c19a6c8dd7 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -25,6 +25,15 @@ module geometry logical(C_BOOL) :: sense; end function surface_sense_c + pure subroutine surface_reflect_c(surf_ind, xyz, uvw) & + bind(C, name='surface_reflect') + use ISO_C_BINDING + implicit none + integer(C_INT), intent(in), value :: surf_ind; + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + end subroutine surface_reflect_c + pure function surface_distance_c(surf_ind, xyz, uvw, coincident) & bind(C, name='surface_distance') result(d) use ISO_C_BINDING @@ -525,6 +534,7 @@ contains real(8) :: d_surf ! distance to surface real(8) :: x0,y0,z0 ! coefficients for surface real(8) :: xyz_cross(3) ! coordinates at projected surface crossing + real(8) :: surf_uvw(3) ! surface normal direction logical :: coincident ! is particle on surface? type(Cell), pointer :: c class(Surface), pointer :: surf @@ -782,9 +792,8 @@ contains ! traveling into if the surface is crossed if (.not. c % simple) then xyz_cross(:) = p % coord(j) % xyz + d_surf*p % coord(j) % uvw - surf => surfaces(abs(level_surf_cross)) % obj - if (dot_product(p % coord(j) % uvw, & - surf % normal(xyz_cross)) > ZERO) then + call surface_normal_c(abs(level_surf_cross)-1, xyz_cross, surf_uvw) + if (dot_product(p % coord(j) % uvw, surf_uvw) > ZERO) then surface_crossed = abs(level_surf_cross) else surface_crossed = -abs(level_surf_cross) diff --git a/src/surface_header.C b/src/surface_header.C index 23fe5adb35..45fb62399e 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -233,8 +233,8 @@ class SurfaceXPlane : public PeriodicSurface public: SurfaceXPlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - const bool coincident) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; void normal(const double xyz[3], double uvw[3]) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; @@ -416,8 +416,8 @@ class SurfacePlane : public PeriodicSurface public: SurfacePlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - const bool coincident) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; void normal(const double xyz[3], double uvw[3]) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; @@ -1138,6 +1138,12 @@ surface_sense(int surf_ind, double xyz[3], double uvw[3]) return surfaces_c[surf_ind]->sense(xyz, uvw); } +extern "C" void +surface_reflect(int surf_ind, double xyz[3], double uvw[3]) +{ + surfaces_c[surf_ind]->reflect(xyz, uvw); +} + extern "C" double surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) { diff --git a/src/surface_header.F90 b/src/surface_header.F90 index d9a00170ba..d632903871 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -2,7 +2,7 @@ module surface_header use, intrinsic :: ISO_C_BINDING - use constants, only: NONE, ONE, TWO, ZERO, HALF, INFINITY, FP_COINCIDENT + use constants, only: NONE use dict_header, only: DictIntInt implicit none @@ -20,20 +20,8 @@ module surface_header integer :: bc ! Boundary condition integer :: i_periodic = NONE ! Index of corresponding periodic surface character(len=104) :: name = "" ! User-defined name - contains - procedure :: reflect - procedure(surface_normal_), deferred :: normal end type Surface - abstract interface - 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 surface_normal_ - end interface - !=============================================================================== ! SURFACECONTAINER allows us to store an array of different types of surfaces !=============================================================================== @@ -50,22 +38,16 @@ module surface_header type, extends(Surface) :: SurfaceXPlane ! x = x0 real(8) :: x0 - contains - procedure :: normal => x_plane_normal end type SurfaceXPlane type, extends(Surface) :: SurfaceYPlane ! y = y0 real(8) :: y0 - contains - procedure :: normal => y_plane_normal end type SurfaceYPlane type, extends(Surface) :: SurfaceZPlane ! z = z0 real(8) :: z0 - contains - procedure :: normal => z_plane_normal end type SurfaceZPlane type, extends(Surface) :: SurfacePlane @@ -74,8 +56,6 @@ module surface_header real(8) :: B real(8) :: C real(8) :: D - contains - procedure :: normal => plane_normal end type SurfacePlane type, extends(Surface) :: SurfaceXCylinder @@ -83,8 +63,6 @@ module surface_header real(8) :: y0 real(8) :: z0 real(8) :: r - contains - procedure :: normal => x_cylinder_normal end type SurfaceXCylinder type, extends(Surface) :: SurfaceYCylinder @@ -92,8 +70,6 @@ module surface_header real(8) :: x0 real(8) :: z0 real(8) :: r - contains - procedure :: normal => y_cylinder_normal end type SurfaceYCylinder type, extends(Surface) :: SurfaceZCylinder @@ -101,8 +77,6 @@ module surface_header real(8) :: x0 real(8) :: y0 real(8) :: r - contains - procedure :: normal => z_cylinder_normal end type SurfaceZCylinder type, extends(Surface) :: SurfaceSphere @@ -111,8 +85,6 @@ module surface_header real(8) :: y0 real(8) :: z0 real(8) :: r - contains - procedure :: normal => sphere_normal end type SurfaceSphere type, extends(Surface) :: SurfaceXCone @@ -121,8 +93,6 @@ module surface_header real(8) :: y0 real(8) :: z0 real(8) :: r2 - contains - procedure :: normal => x_cone_normal end type SurfaceXCone type, extends(Surface) :: SurfaceYCone @@ -131,8 +101,6 @@ module surface_header real(8) :: y0 real(8) :: z0 real(8) :: r2 - contains - procedure :: normal => y_cone_normal end type SurfaceYCone type, extends(Surface) :: SurfaceZCone @@ -141,15 +109,11 @@ module surface_header real(8) :: y0 real(8) :: z0 real(8) :: r2 - contains - procedure :: normal => z_cone_normal end type SurfaceZCone type, extends(Surface) :: SurfaceQuadric ! Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 real(8) :: A, B, C, D, E, F, G, H, J, K - contains - procedure :: normal => quadric_normal end type SurfaceQuadric integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces @@ -161,194 +125,6 @@ module surface_header contains -!=============================================================================== -! REFLECT determines the direction a particle will travel if it is specularly -! reflected from the surface at a given position and direction. The position is -! needed because the reflection is performed using the surface normal, which -! depends on the position for second-order surfaces. -!=============================================================================== - - pure subroutine reflect(this, xyz, uvw) - class(Surface), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8), intent(inout) :: uvw(3) - - real(8) :: projection - real(8) :: magnitude - real(8) :: n(3) - - ! Construct normal vector - n(:) = this%normal(xyz) - - ! Determine projection of direction onto normal and squared magnitude of - ! normal - projection = n(1)*uvw(1) + n(2)*uvw(2) + n(3)*uvw(3) - magnitude = n(1)*n(1) + n(2)*n(2) + n(3)*n(3) - - ! Reflect direction according to normal - uvw(:) = uvw - TWO*projection/magnitude * n - end subroutine reflect - -!=============================================================================== -! SurfaceXPlane Implementation -!=============================================================================== - - pure function x_plane_normal(this, xyz) result(uvw) - class(SurfaceXPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ONE, ZERO, ZERO] - end function x_plane_normal - -!=============================================================================== -! SurfaceYPlane Implementation -!=============================================================================== - - pure function y_plane_normal(this, xyz) result(uvw) - class(SurfaceYPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ZERO, ONE, ZERO] - end function y_plane_normal - -!=============================================================================== -! SurfaceZPlane Implementation -!=============================================================================== - - pure function z_plane_normal(this, xyz) result(uvw) - class(SurfaceZPlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [ZERO, ZERO, ONE] - end function z_plane_normal - -!=============================================================================== -! SurfacePlane Implementation -!=============================================================================== - - pure function plane_normal(this, xyz) result(uvw) - class(SurfacePlane), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = [this%A, this%B, this%C] - end function plane_normal - -!=============================================================================== -! SurfaceXCylinder Implementation -!=============================================================================== - - pure function x_cylinder_normal(this, xyz) result(uvw) - class(SurfaceXCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = ZERO - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function x_cylinder_normal - -!=============================================================================== -! SurfaceYCylinder Implementation -!=============================================================================== - - pure function y_cylinder_normal(this, xyz) result(uvw) - class(SurfaceYCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = ZERO - uvw(3) = TWO*(xyz(3) - this%z0) - end function y_cylinder_normal - -!=============================================================================== -! SurfaceZCylinder Implementation -!=============================================================================== - - pure function z_cylinder_normal(this, xyz) result(uvw) - class(SurfaceZCylinder), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = ZERO - end function z_cylinder_normal - -!=============================================================================== -! SurfaceSphere Implementation -!=============================================================================== - - pure function sphere_normal(this, xyz) result(uvw) - class(SurfaceSphere), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(:) = TWO*(xyz - [this%x0, this%y0, this%z0]) - end function sphere_normal - -!=============================================================================== -! SurfaceXCone Implementation -!=============================================================================== - - pure function x_cone_normal(this, xyz) result(uvw) - class(SurfaceXCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = -TWO*this%r2*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function x_cone_normal - -!=============================================================================== -! SurfaceYCone Implementation -!=============================================================================== - - pure function y_cone_normal(this, xyz) result(uvw) - class(SurfaceYCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = -TWO*this%r2*(xyz(2) - this%y0) - uvw(3) = TWO*(xyz(3) - this%z0) - end function y_cone_normal - -!=============================================================================== -! SurfaceZCone Implementation -!=============================================================================== - - pure function z_cone_normal(this, xyz) result(uvw) - class(SurfaceZCone), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - uvw(1) = TWO*(xyz(1) - this%x0) - uvw(2) = TWO*(xyz(2) - this%y0) - uvw(3) = -TWO*this%r2*(xyz(3) - this%z0) - end function z_cone_normal - -!=============================================================================== -! SurfaceQuadric Implementation -!=============================================================================== - - pure function quadric_normal(this, xyz) result(uvw) - class(SurfaceQuadric), intent(in) :: this - real(8), intent(in) :: xyz(3) - real(8) :: uvw(3) - - associate (x => xyz(1), y => xyz(2), z => xyz(3)) - uvw(1) = TWO*this%A*x + this%D*y + this%F*z + this%G - uvw(2) = TWO*this%B*y + this%D*x + this%E*z + this%H - uvw(3) = TWO*this%C*z + this%E*y + this%F*x + this%J - end associate - end function quadric_normal - !=============================================================================== ! FREE_MEMORY_SURFACES deallocates global arrays defined in this module !=============================================================================== diff --git a/src/tracking.F90 b/src/tracking.F90 index 4f0f110bc7..d616212ec6 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -5,7 +5,8 @@ module tracking use error, only: fatal_error, warning, write_message use geometry_header, only: cells use geometry, only: find_cell, distance_to_boundary, cross_lattice, & - check_cell_overlap, surface_periodic_c + check_cell_overlap, surface_reflect_c, & + surface_periodic_c use message_passing use mgxs_header use nuclide_header @@ -354,7 +355,7 @@ contains end if ! Reflect particle off surface - call surf%reflect(p%coord(1)%xyz, p%coord(1)%uvw) + call surface_reflect_c(i_surface-1, p%coord(1)%xyz, p%coord(1)%uvw) ! Make sure new particle direction is normalized u = p%coord(1)%uvw(1) From 81ba835d145700fb298b24c25414ca9864b7767b Mon Sep 17 00:00:00 2001 From: Giud Date: Fri, 19 Jan 2018 10:14:43 -0500 Subject: [PATCH 022/212] if cant find cell in which particle is, calls mark_as_lost instead of fatal_error --- src/tracking.F90 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/tracking.F90 b/src/tracking.F90 index 65769a7f18..f651517019 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -2,7 +2,7 @@ module tracking use constants use cross_section, only: calculate_xs - use error, only: fatal_error, warning, write_message + use error, only: warning, write_message use geometry_header, only: cells use geometry, only: find_cell, distance_to_boundary, cross_lattice, & check_cell_overlap @@ -85,7 +85,9 @@ contains if (p % coord(p % n_coord) % cell == NONE) then call find_cell(p, found_cell) if (.not. found_cell) then - call fatal_error("Could not locate particle " // trim(to_str(p % id))) + call p % mark_as_lost("Could not find the cell containing" & + // " particle " // trim(to_str(p %id))) + return end if ! set birth cell attribute From 57991b271db4828e8fbc92fbdf78b5892f83fb7d Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 19 Jan 2018 18:12:57 -0500 Subject: [PATCH 023/212] Start moving surface->summary.h5 to C++ --- CMakeLists.txt | 5 +- src/api.F90 | 2 +- src/cmfd_execute.F90 | 8 +- src/eigenvalue.F90 | 18 ++-- src/error.F90 | 4 +- src/geometry.F90 | 1 - src/hdf5_interface.F90 | 4 +- src/hdf5_interface.h | 47 ++++++++++ src/initialize.F90 | 12 +-- src/input_xml.F90 | 80 +++-------------- src/main.F90 | 8 +- src/mesh.F90 | 4 +- src/message_passing.F90 | 6 +- src/output.F90 | 2 +- src/simulation.F90 | 8 +- src/source.F90 | 2 +- src/state_point.F90 | 18 ++-- src/summary.F90 | 92 +++----------------- src/surface_header.C | 184 +++++++++++++++++++++++++++++++++++++++- src/surface_header.F90 | 45 ---------- src/tallies/tally.F90 | 4 +- src/tallies/trigger.F90 | 2 +- src/volume_calc.F90 | 6 +- 23 files changed, 311 insertions(+), 251 deletions(-) create mode 100644 src/hdf5_interface.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 200d836fe1..58fb55e799 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,14 +48,14 @@ add_definitions(-DMAX_COORD=${maxcoord}) set(MPI_ENABLED FALSE) if($ENV{FC} MATCHES "(mpi[^/]*|ftn)$") message("-- Detected MPI wrapper: $ENV{FC}") - add_definitions(-DMPI) + add_definitions(-DOPENMC_MPI) set(MPI_ENABLED TRUE) endif() # Check for Fortran 2008 MPI interface if(MPI_ENABLED AND mpif08) message("-- Using Fortran 2008 MPI bindings") - add_definitions(-DMPIF08) + add_definitions(-DOPENMC_MPIF08) endif() #=============================================================================== @@ -435,6 +435,7 @@ set(LIBOPENMC_FORTRAN_SRC src/tallies/trigger_header.F90 ) set(LIBOPENMC_CXX_SRC + src/hdf5_interface.h src/random_lcg.h src/random_lcg.cpp src/surface_header.C diff --git a/src/api.F90 b/src/api.F90 index eb9a996950..5d56b857ca 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -171,7 +171,7 @@ contains ! Close FORTRAN interface. call h5close_f(err) -#ifdef MPI +#ifdef OPENMC_MPI ! Free all MPI types call MPI_TYPE_FREE(MPI_BANK, err) #endif diff --git a/src/cmfd_execute.F90 b/src/cmfd_execute.F90 index 9cdb751a40..af8d57a807 100644 --- a/src/cmfd_execute.F90 +++ b/src/cmfd_execute.F90 @@ -105,7 +105,7 @@ contains real(8) :: hxyz(3) ! cell dimensions of current ijk cell real(8) :: vol ! volume of cell real(8),allocatable :: source(:,:,:,:) ! tmp source array for entropy -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif @@ -197,7 +197,7 @@ contains end if -#ifdef MPI +#ifdef OPENMC_MPI ! Broadcast full source to all procs call MPI_BCAST(cmfd % cmfd_src, n, MPI_REAL8, 0, mpi_intracomm, mpi_err) #endif @@ -234,7 +234,7 @@ contains real(8) :: norm ! normalization factor logical :: outside ! any source sites outside mesh logical :: in_mesh ! source site is inside mesh -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err #endif @@ -291,7 +291,7 @@ contains if (.not. cmfd_feedback) return ! Broadcast weight factors to all procs -#ifdef MPI +#ifdef OPENMC_MPI call MPI_BCAST(cmfd % weightfactors, ng*nx*ny*nz, MPI_REAL8, 0, & mpi_intracomm, mpi_err) #endif diff --git a/src/eigenvalue.F90 b/src/eigenvalue.F90 index 27ae4063ea..7a11d1fb48 100644 --- a/src/eigenvalue.F90 +++ b/src/eigenvalue.F90 @@ -42,11 +42,11 @@ contains type(Bank), save, allocatable :: & & temp_sites(:) ! local array of extra sites on each node -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code integer(8) :: n ! number of sites to send/recv integer :: neighbor ! processor to send/recv data from -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Request) :: request(20) #else integer :: request(20) ! communication request for send/recving sites @@ -66,7 +66,7 @@ contains ! fission bank its own sites starts in order to ensure reproducibility by ! skipping ahead to the proper seed. -#ifdef MPI +#ifdef OPENMC_MPI start = 0_8 call MPI_EXSCAN(n_bank, start, 1, MPI_INTEGER8, MPI_SUM, & mpi_intracomm, mpi_err) @@ -148,7 +148,7 @@ contains ! neighboring processors, we have to perform an ALLGATHER to determine the ! indices for all processors -#ifdef MPI +#ifdef OPENMC_MPI ! First do an exclusive scan to get the starting indices for start = 0_8 call MPI_EXSCAN(index_temp, start, 1, MPI_INTEGER8, MPI_SUM, & @@ -191,7 +191,7 @@ contains call time_bank_sample % stop() call time_bank_sendrecv % start() -#ifdef MPI +#ifdef OPENMC_MPI ! ========================================================================== ! SEND BANK SITES TO NEIGHBORS @@ -343,14 +343,14 @@ contains subroutine calculate_generation_keff() real(8) :: keff_reduced -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif ! Get keff for this generation by subtracting off the starting value keff_generation = global_tallies(RESULT_VALUE, K_TRACKLENGTH) - keff_generation -#ifdef MPI +#ifdef OPENMC_MPI ! Combine values across all processors call MPI_ALLREDUCE(keff_generation, keff_reduced, 1, MPI_REAL8, & MPI_SUM, mpi_intracomm, mpi_err) @@ -584,7 +584,7 @@ contains real(8) :: total ! total weight in source bank logical :: sites_outside ! were there sites outside the ufs mesh? -#ifdef MPI +#ifdef OPENMC_MPI integer :: n ! total number of ufs mesh cells integer :: mpi_err ! MPI error code #endif @@ -608,7 +608,7 @@ contains call fatal_error("Source sites outside of the UFS mesh!") end if -#ifdef MPI +#ifdef OPENMC_MPI ! Send source fraction to all processors n = product(m % dimension) call MPI_BCAST(source_frac, n, MPI_REAL8, 0, mpi_intracomm, mpi_err) diff --git a/src/error.F90 b/src/error.F90 index 27004d729a..ae02e0897d 100644 --- a/src/error.F90 +++ b/src/error.F90 @@ -128,7 +128,7 @@ contains integer :: line_wrap ! length of line integer :: length ! length of message integer :: indent ! length of indentation -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err #endif @@ -180,7 +180,7 @@ contains end if end do -#ifdef MPI +#ifdef OPENMC_MPI ! Abort MPI call MPI_ABORT(mpi_intracomm, code, mpi_err) #endif diff --git a/src/geometry.F90 b/src/geometry.F90 index c19a6c8dd7..f1feb3ba30 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -537,7 +537,6 @@ contains real(8) :: surf_uvw(3) ! surface normal direction logical :: coincident ! is particle on surface? type(Cell), pointer :: c - class(Surface), pointer :: surf class(Lattice), pointer :: lat ! inialize distance to infinity (huge) diff --git a/src/hdf5_interface.F90 b/src/hdf5_interface.F90 index e8c39b923c..410149d9e7 100644 --- a/src/hdf5_interface.F90 +++ b/src/hdf5_interface.F90 @@ -124,7 +124,7 @@ contains ! Setup file access property list with parallel I/O access call h5pcreate_f(H5P_FILE_ACCESS_F, plist, hdf5_err) #ifdef PHDF5 -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 call h5pset_fapl_mpio_f(plist, mpi_intracomm%MPI_VAL, & MPI_INFO_NULL%MPI_VAL, hdf5_err) #else @@ -174,7 +174,7 @@ contains ! Setup file access property list with parallel I/O access call h5pcreate_f(H5P_FILE_ACCESS_F, plist, hdf5_err) #ifdef PHDF5 -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 call h5pset_fapl_mpio_f(plist, mpi_intracomm%MPI_VAL, & MPI_INFO_NULL%MPI_VAL, hdf5_err) #else diff --git a/src/hdf5_interface.h b/src/hdf5_interface.h new file mode 100644 index 0000000000..38bb7d88bc --- /dev/null +++ b/src/hdf5_interface.h @@ -0,0 +1,47 @@ +#ifndef HDF5_INTERFACE_H +#define HDF5_INTERFACE_H + +#include // For std::array +#include // For strlen + +#include "hdf5.h" + + +template void +write_double_1D(hid_t group_id, char const *name, + std::array &buffer) +{ + hsize_t dims[1]{array_len}; + hid_t dataspace = H5Screate_simple(1, dims, NULL); + + hid_t dataset = H5Dcreate(group_id, name, H5T_NATIVE_DOUBLE, dataspace, + H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + + H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, + &buffer[0]); + + H5Sclose(dataspace); + H5Dclose(dataset); +} + + +void +write_string(hid_t group_id, char const *name, char const *buffer) +{ + size_t buffer_len = strlen(buffer); + hid_t datatype = H5Tcopy(H5T_C_S1); + H5Tset_size(datatype, buffer_len); + + hid_t dataspace = H5Screate(H5S_SCALAR); + + hid_t dataset = H5Dcreate(group_id, name, datatype, dataspace, + H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + + H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); + + H5Tclose(datatype); + H5Sclose(dataspace); + H5Dclose(dataset); +} + +#endif //HDF5_INTERFACE_H diff --git a/src/initialize.F90 b/src/initialize.F90 index dd7894f96b..2af93627ea 100644 --- a/src/initialize.F90 +++ b/src/initialize.F90 @@ -52,8 +52,8 @@ contains ! Copy the communicator to a new variable. This is done to avoid changing ! the signature of this subroutine. If MPI is being used but no communicator ! was passed, assume MPI_COMM_WORLD. -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 type(MPI_Comm), intent(in) :: comm ! MPI intracommunicator if (present(intracomm)) then comm % MPI_VAL = intracomm @@ -74,7 +74,7 @@ contains call time_total%start() call time_initialize%start() -#ifdef MPI +#ifdef OPENMC_MPI ! Setup MPI call initialize_mpi(comm) #endif @@ -108,7 +108,7 @@ contains end subroutine openmc_init -#ifdef MPI +#ifdef OPENMC_MPI !=============================================================================== ! INITIALIZE_MPI starts up the Message Passing Interface (MPI) and determines ! the number of processors the problem is being run with as well as the rank of @@ -116,7 +116,7 @@ contains !=============================================================================== subroutine initialize_mpi(intracomm) -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Comm), intent(in) :: intracomm ! MPI intracommunicator #else integer, intent(in) :: intracomm ! MPI intracommunicator @@ -124,7 +124,7 @@ contains integer :: mpi_err ! MPI error code integer :: bank_blocks(5) ! Count for each datatype -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Datatype) :: bank_types(5) #else integer :: bank_types(5) ! Datatypes diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 4994ff76bc..462b9708f9 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -54,7 +54,7 @@ module input_xml implicit none type(C_PTR) :: node_ptr end subroutine read_surfaces - end interface + end interface contains @@ -1081,77 +1081,23 @@ contains select type(s) type is (SurfaceXPlane) - s%x0 = coeffs(1) - ! Determine outer surfaces - xmin = min(xmin, s % x0) - xmax = max(xmax, s % x0) - if (xmin == s % x0) i_xmin = i - if (xmax == s % x0) i_xmax = i + xmin = min(xmin, coeffs(1)) + xmax = max(xmax, coeffs(1)) + if (xmin == coeffs(1)) i_xmin = i + if (xmax == coeffs(1)) i_xmax = i type is (SurfaceYPlane) - s%y0 = coeffs(1) - ! Determine outer surfaces - ymin = min(ymin, s % y0) - ymax = max(ymax, s % y0) - if (ymin == s % y0) i_ymin = i - if (ymax == s % y0) i_ymax = i + ymin = min(ymin, coeffs(1)) + ymax = max(ymax, coeffs(1)) + if (ymin == coeffs(1)) i_ymin = i + if (ymax == coeffs(1)) i_ymax = i type is (SurfaceZPlane) - s%z0 = coeffs(1) - ! Determine outer surfaces - zmin = min(zmin, s % z0) - zmax = max(zmax, s % z0) - if (zmin == s % z0) i_zmin = i - if (zmax == s % z0) i_zmax = i - type is (SurfacePlane) - s%A = coeffs(1) - s%B = coeffs(2) - s%C = coeffs(3) - s%D = coeffs(4) - type is (SurfaceXCylinder) - s%y0 = coeffs(1) - s%z0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceYCylinder) - s%x0 = coeffs(1) - s%z0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceZCylinder) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%r = coeffs(3) - type is (SurfaceSphere) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r = coeffs(4) - type is (SurfaceXCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceYCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceZCone) - s%x0 = coeffs(1) - s%y0 = coeffs(2) - s%z0 = coeffs(3) - s%r2 = coeffs(4) - type is (SurfaceQuadric) - s%A = coeffs(1) - s%B = coeffs(2) - s%C = coeffs(3) - s%D = coeffs(4) - s%E = coeffs(5) - s%F = coeffs(6) - s%G = coeffs(7) - s%H = coeffs(8) - s%J = coeffs(9) - s%K = coeffs(10) + zmin = min(zmin, coeffs(1)) + zmax = max(zmax, coeffs(1)) + if (zmin == coeffs(1)) i_zmin = i + if (zmax == coeffs(1)) i_zmax = i end select ! No longer need coefficients diff --git a/src/main.F90 b/src/main.F90 index d8e52643c1..120bdd1e0c 100644 --- a/src/main.F90 +++ b/src/main.F90 @@ -9,13 +9,13 @@ program main implicit none -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif ! Initialize run -- when run with MPI, pass communicator -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 call openmc_init(MPI_COMM_WORLD % MPI_VAL) #else call openmc_init(MPI_COMM_WORLD) @@ -39,7 +39,7 @@ program main ! finalize run call openmc_finalize() -#ifdef MPI +#ifdef OPENMC_MPI ! If MPI is in use and enabled, terminate it call MPI_FINALIZE(mpi_err) #endif diff --git a/src/mesh.F90 b/src/mesh.F90 index e997890a4a..790dc7d889 100644 --- a/src/mesh.F90 +++ b/src/mesh.F90 @@ -34,7 +34,7 @@ contains integer :: n ! number of energy groups / size integer :: mesh_bin ! mesh bin integer :: e_bin ! energy bin -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif logical :: outside ! was any site outside mesh? @@ -86,7 +86,7 @@ contains cnt_(e_bin, mesh_bin) = cnt_(e_bin, mesh_bin) + bank_array(i) % wgt end do FISSION_SITES -#ifdef MPI +#ifdef OPENMC_MPI ! collect values from all processors n = size(cnt_) call MPI_REDUCE(cnt_, cnt, n, MPI_REAL8, MPI_SUM, 0, mpi_intracomm, mpi_err) diff --git a/src/message_passing.F90 b/src/message_passing.F90 index 0f2b94d1af..7391a632c7 100644 --- a/src/message_passing.F90 +++ b/src/message_passing.F90 @@ -1,7 +1,7 @@ module message_passing -#ifdef MPI -#ifdef MPIF08 +#ifdef OPENMC_MPI +#ifdef OPENMC_MPIF08 use mpi_f08 #else use mpi @@ -16,7 +16,7 @@ module message_passing integer :: rank = 0 ! rank of process logical :: master = .true. ! master process? logical :: mpi_enabled = .false. ! is MPI in use and initialized? -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Datatype) :: MPI_BANK ! MPI datatype for fission bank type(MPI_Comm) :: mpi_intracomm ! MPI intra-communicator #else diff --git a/src/output.F90 b/src/output.F90 index 9a144721dc..1b7cae121e 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -88,7 +88,7 @@ contains ! Write the date and time write(UNIT=OUTPUT_UNIT, FMT='(9X,"Date/Time | ",A)') time_stamp() -#ifdef MPI +#ifdef OPENMC_MPI ! Write number of processors write(UNIT=OUTPUT_UNIT, FMT='(5X,"MPI Processes | ",A)') & trim(to_str(n_procs)) diff --git a/src/simulation.F90 b/src/simulation.F90 index ef29e7832b..24e9b29fc3 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -320,7 +320,7 @@ contains subroutine finalize_batch() -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code #endif @@ -342,7 +342,7 @@ contains ! Check_triggers if (master) call check_triggers() -#ifdef MPI +#ifdef OPENMC_MPI call MPI_BCAST(satisfy_triggers, 1, MPI_LOGICAL, 0, & mpi_intracomm, mpi_err) #endif @@ -469,7 +469,7 @@ contains subroutine openmc_simulation_finalize() bind(C) integer :: i ! loop index -#ifdef MPI +#ifdef OPENMC_MPI integer :: n ! size of arrays integer :: mpi_err ! MPI error code integer(8) :: temp @@ -494,7 +494,7 @@ contains ! Increment total number of generations total_gen = total_gen + current_batch*gen_per_batch -#ifdef MPI +#ifdef OPENMC_MPI ! Broadcast tally results so that each process has access to results if (allocated(tallies)) then do i = 1, size(tallies) diff --git a/src/source.F90 b/src/source.F90 index 557120e979..5beecd8870 100644 --- a/src/source.F90 +++ b/src/source.F90 @@ -1,7 +1,7 @@ module source use hdf5, only: HID_T -#ifdef MPI +#ifdef OPENMC_MPI use message_passing #endif diff --git a/src/state_point.F90 b/src/state_point.F90 index f7a8928987..ba7bcef19d 100644 --- a/src/state_point.F90 +++ b/src/state_point.F90 @@ -523,7 +523,7 @@ contains integer(HID_T) :: tallies_group, tally_group real(8), allocatable :: tally_temp(:,:,:) ! contiguous array of results real(8), target :: global_temp(3,N_GLOBAL_TALLIES) -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code real(8) :: dummy ! temporary receive buffer for non-root reduces #endif @@ -543,7 +543,7 @@ contains end if -#ifdef MPI +#ifdef OPENMC_MPI ! Reduce global tallies n_bins = size(global_tallies) call MPI_REDUCE(global_tallies, global_temp, n_bins, MPI_REAL8, MPI_SUM, & @@ -586,7 +586,7 @@ contains ! The MPI_IN_PLACE specifier allows the master to copy values into ! a receive buffer without having a temporary variable -#ifdef MPI +#ifdef OPENMC_MPI call MPI_REDUCE(MPI_IN_PLACE, tally_temp, n_bins, MPI_REAL8, & MPI_SUM, 0, mpi_intracomm, mpi_err) #endif @@ -610,7 +610,7 @@ contains deallocate(dummy_tally % results) else ! Receive buffer not significant at other processors -#ifdef MPI +#ifdef OPENMC_MPI call MPI_REDUCE(tally_temp, dummy, n_bins, MPI_REAL8, MPI_SUM, & 0, mpi_intracomm, mpi_err) #endif @@ -849,7 +849,7 @@ contains integer(HID_T) :: plist ! property list #else integer :: i -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code type(Bank), allocatable, target :: temp_source(:) #endif @@ -897,7 +897,7 @@ contains dspace, dset, hdf5_err) ! Save source bank sites since the souce_bank array is overwritten below -#ifdef MPI +#ifdef OPENMC_MPI allocate(temp_source(work)) temp_source(:) = source_bank(:) #endif @@ -907,7 +907,7 @@ contains dims(1) = work_index(i+1) - work_index(i) call h5screate_simple_f(1, dims, memspace, hdf5_err) -#ifdef MPI +#ifdef OPENMC_MPI ! Receive source sites from other processes if (i > 0) then call MPI_RECV(source_bank, int(dims(1)), MPI_BANK, i, i, & @@ -933,12 +933,12 @@ contains call h5dclose_f(dset, hdf5_err) ! Restore state of source bank -#ifdef MPI +#ifdef OPENMC_MPI source_bank(:) = temp_source(:) deallocate(temp_source) #endif else -#ifdef MPI +#ifdef OPENMC_MPI call MPI_SEND(source_bank, int(work), MPI_BANK, 0, rank, & mpi_intracomm, mpi_err) #endif diff --git a/src/summary.F90 b/src/summary.F90 index 0f45ef1bbd..ca72764073 100644 --- a/src/summary.F90 +++ b/src/summary.F90 @@ -24,6 +24,17 @@ module summary public :: write_summary + interface + subroutine surface_to_hdf5_c(surf_ind, group) & + bind(C, name='surface_to_hdf5') + use ISO_C_BINDING + use hdf5 + implicit none + integer(C_INT), intent(in), value :: surf_ind + integer(HID_T), intent(in), value :: group + end subroutine surface_to_hdf5_c + end interface + contains !=============================================================================== @@ -125,7 +136,6 @@ contains integer(HID_T) :: surfaces_group, surface_group integer(HID_T) :: universes_group, univ_group integer(HID_T) :: lattices_group, lattice_group - real(8), allocatable :: coeffs(:) character(:), allocatable :: region_spec type(Cell), pointer :: c class(Surface), pointer :: s @@ -245,87 +255,11 @@ contains surface_group = create_group(surfaces_group, "surface " // & trim(to_str(s%id))) + call surface_to_hdf5_c(i-1, surface_group) + ! Write name for this surface call write_dataset(surface_group, "name", s%name) - ! Write surface type - select type (s) - type is (SurfaceXPlane) - call write_dataset(surface_group, "type", "x-plane") - allocate(coeffs(1)) - coeffs(1) = s%x0 - - type is (SurfaceYPlane) - call write_dataset(surface_group, "type", "y-plane") - allocate(coeffs(1)) - coeffs(1) = s%y0 - - type is (SurfaceZPlane) - call write_dataset(surface_group, "type", "z-plane") - allocate(coeffs(1)) - coeffs(1) = s%z0 - - type is (SurfacePlane) - call write_dataset(surface_group, "type", "plane") - allocate(coeffs(4)) - coeffs(:) = [s%A, s%B, s%C, s%D] - - type is (SurfaceXCylinder) - call write_dataset(surface_group, "type", "x-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%y0, s%z0, s%r] - - type is (SurfaceYCylinder) - call write_dataset(surface_group, "type", "y-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%x0, s%z0, s%r] - - type is (SurfaceZCylinder) - call write_dataset(surface_group, "type", "z-cylinder") - allocate(coeffs(3)) - coeffs(:) = [s%x0, s%y0, s%r] - - type is (SurfaceSphere) - call write_dataset(surface_group, "type", "sphere") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r] - - type is (SurfaceXCone) - call write_dataset(surface_group, "type", "x-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceYCone) - call write_dataset(surface_group, "type", "y-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceZCone) - call write_dataset(surface_group, "type", "z-cone") - allocate(coeffs(4)) - coeffs(:) = [s%x0, s%y0, s%z0, s%r2] - - type is (SurfaceQuadric) - call write_dataset(surface_group, "type", "quadric") - allocate(coeffs(10)) - coeffs(:) = [s%A, s%B, s%C, s%D, s%E, s%F, s%G, s%H, s%J, s%K] - - end select - call write_dataset(surface_group, "coefficients", coeffs) - deallocate(coeffs) - - ! Write boundary type - select case (s%bc) - case (BC_TRANSMIT) - call write_dataset(surface_group, "boundary_type", "transmission") - case (BC_VACUUM) - call write_dataset(surface_group, "boundary_type", "vacuum") - case (BC_REFLECT) - call write_dataset(surface_group, "boundary_type", "reflective") - case (BC_PERIODIC) - call write_dataset(surface_group, "boundary_type", "periodic") - end select - call close_group(surface_group) end do SURFACE_LOOP diff --git a/src/surface_header.C b/src/surface_header.C index 45fb62399e..db53c8982e 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -1,8 +1,12 @@ +#include // For std::array #include // For strcmp #include // For numeric_limits #include // For fabs #include "pugixml/pugixml.hpp" +#include "hdf5.h" + +#include "hdf5_interface.h" // DEBUGGING #include @@ -15,6 +19,11 @@ const double FP_COINCIDENT = 1e-12; const double INFTY = std::numeric_limits::max(); +const int BC_TRANSMIT{0}; +const int BC_VACUUM{1}; +const int BC_REFLECT{2}; +const int BC_PERIODIC{3}; + //============================================================================== // Global array of surfaces //============================================================================== @@ -127,6 +136,13 @@ public: //! @param xyz[3] A 3D Cartesian coordinate. //! @param uvw[3] This output argument provides the normal. virtual void normal(const double xyz[3], double uvw[3]) const = 0; + + //! Write all information needed to reconstruct the surface to an HDF5 group. + //! @param group_id An HDF5 group id. + virtual void to_hdf5(hid_t group_id) const = 0; + +protected: + void write_bc_to_hdf5(hid_t group_id) const; }; bool @@ -164,6 +180,25 @@ Surface::reflect(const double xyz[3], double uvw[3]) const uvw[2] -= 2.0 * projection / magnitude * norm[2]; } +void +Surface::write_bc_to_hdf5(hid_t group_id) const +{ + switch(bc) { + case BC_TRANSMIT : + write_string(group_id, "boundary_type", "transmission"); + break; + case BC_VACUUM : + write_string(group_id, "boundary_type", "vacuum"); + break; + case BC_REFLECT : + write_string(group_id, "boundary_type", "reflective"); + break; + case BC_PERIODIC : + write_string(group_id, "boundary_type", "periodic"); + break; + } +} + //============================================================================== //! A `Surface` that supports periodic boundary conditions. //! @@ -236,6 +271,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; @@ -261,6 +297,14 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); } +void SurfaceXPlane::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "x-plane"); + std::array coeffs{{x0}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const { @@ -285,7 +329,7 @@ bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], return true; } -}; +} //============================================================================== // SurfaceYPlane @@ -303,6 +347,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; @@ -328,6 +373,14 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); } +void SurfaceYPlane::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "y-plane"); + std::array coeffs{{y0}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const { @@ -352,7 +405,7 @@ bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], return true; } -}; +} //============================================================================== // SurfaceZPlane @@ -370,6 +423,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; @@ -395,13 +449,21 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); } +void SurfaceZPlane::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "z-plane"); + std::array coeffs{{z0}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const { // Assume the other plane is aligned along z. Just change the z coord. xyz[2] = z0; return false; -}; +} //============================================================================== // SurfacePlane @@ -419,6 +481,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; @@ -457,6 +520,14 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const uvw[2] = C; } +void SurfacePlane::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "plane"); + std::array coeffs{{A, B, C, D}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const { @@ -564,6 +635,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) @@ -588,6 +660,15 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const axis_aligned_cylinder_normal<0, 1, 2>(xyz, uvw, y0, z0); } + +void SurfaceXCylinder::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "x-cylinder"); + std::array coeffs{{y0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceYCylinder //! A cylinder aligned along the y-axis. @@ -605,6 +686,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) @@ -629,6 +711,14 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const axis_aligned_cylinder_normal<1, 0, 2>(xyz, uvw, x0, z0); } +void SurfaceYCylinder::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "y-cylinder"); + std::array coeffs{{x0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceZCylinder //! A cylinder aligned along the z-axis. @@ -646,6 +736,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) @@ -670,6 +761,14 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); } +void SurfaceZCylinder::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "z-cylinder"); + std::array coeffs{{x0, y0, r}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceSphere //! A sphere. @@ -687,6 +786,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) @@ -748,6 +848,14 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const uvw[2] = 2.0 * (xyz[2] - z0); } +void SurfaceSphere::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "sphere"); + std::array coeffs{{x0, y0, z0, r}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // Generic functions for x-, y-, and z-, cones //============================================================================== @@ -848,6 +956,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) @@ -872,6 +981,14 @@ inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<0, 1, 2>(xyz, uvw, x0, y0, z0, r_sq); } +void SurfaceXCone::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "x-cone"); + std::array coeffs{{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceYCone //! A cone aligned along the y-axis. @@ -889,6 +1006,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) @@ -913,6 +1031,14 @@ inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<1, 0, 2>(xyz, uvw, y0, x0, z0, r_sq); } +void SurfaceYCone::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "y-cone"); + std::array coeffs{{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceZCone //! A cone aligned along the z-axis. @@ -930,6 +1056,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) @@ -954,6 +1081,14 @@ inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<2, 0, 1>(xyz, uvw, z0, x0, y0, r_sq); } +void SurfaceZCone::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "z-cone"); + std::array coeffs{{x0, y0, z0, r_sq}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== // SurfaceQuadric //! A general surface described by a quadratic equation. @@ -971,6 +1106,7 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5(hid_t group_id) const; }; SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) @@ -1055,6 +1191,14 @@ SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const uvw[2] = 2.0*C*z + E*y + F*x + J; } +void SurfaceQuadric::to_hdf5(hid_t group_id) const +{ + write_string(group_id, "type", "quadric"); + std::array coeffs{{A, B, C, D, E, F, G, H, J, K}}; + write_double_1D(group_id, "coefficients", coeffs); + write_bc_to_hdf5(group_id); +} + //============================================================================== extern "C" void @@ -1084,6 +1228,7 @@ read_surfaces(pugi::xml_node *node) } else { std::cout << "ERROR: Found a surface with no type attribute/node" << std::endl; + //TODO: call fatal_error } if (strcmp(surf_type, "x-plane") == 0) { @@ -1125,6 +1270,33 @@ read_surfaces(pugi::xml_node *node) } else { std::cout << "Call error or handle uppercase here!" << std::endl; std::cout << surf_type << std::endl; + //TODO: call fatal_error + } + + const pugi::char_t *surf_bc{""}; + if (surf_node.attribute("boundary")) { + surf_bc = surf_node.attribute("boundary").value(); + } else if (surf_node.child("boundary")) { + surf_bc = surf_node.attribute("boundary").value(); + } + + if (strcmp(surf_bc, "transmission") == 0 + or strcmp(surf_bc, "transmit") == 0 + or strcmp(surf_bc, "") == 0) { + surfaces_c[i_surf]->bc = BC_TRANSMIT; + + } else if (strcmp(surf_bc, "vacuum") == 0) { + surfaces_c[i_surf]->bc = BC_VACUUM; + + } else if (strcmp(surf_bc, "reflective") == 0 + or strcmp(surf_bc, "reflect") == 0 + or strcmp(surf_bc, "reflecting") == 0) { + surfaces_c[i_surf]->bc = BC_REFLECT; + } else if (strcmp(surf_bc, "periodic") == 0) { + surfaces_c[i_surf]->bc = BC_PERIODIC; + } else { + std::cout << "Unknown boundary condition" << std::endl; + //TODO: call fatal_error } } } @@ -1156,6 +1328,12 @@ surface_normal(int surf_ind, double xyz[3], double uvw[3]) return surfaces_c[surf_ind]->normal(xyz, uvw); } +extern "C" void +surface_to_hdf5(int surf_ind, hid_t group) +{ + surfaces_c[surf_ind]->to_hdf5(group); +} + extern "C" bool surface_periodic(int surf_ind1, int surf_ind2, double xyz[3], double uvw[3]) { diff --git a/src/surface_header.F90 b/src/surface_header.F90 index d632903871..98e2423b62 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -36,84 +36,39 @@ module surface_header !=============================================================================== type, extends(Surface) :: SurfaceXPlane - ! x = x0 - real(8) :: x0 end type SurfaceXPlane type, extends(Surface) :: SurfaceYPlane - ! y = y0 - real(8) :: y0 end type SurfaceYPlane type, extends(Surface) :: SurfaceZPlane - ! z = z0 - real(8) :: z0 end type SurfaceZPlane type, extends(Surface) :: SurfacePlane - ! Ax + By + Cz = D - real(8) :: A - real(8) :: B - real(8) :: C - real(8) :: D end type SurfacePlane type, extends(Surface) :: SurfaceXCylinder - ! (y - y0)^2 + (z - z0)^2 = R^2 - real(8) :: y0 - real(8) :: z0 - real(8) :: r end type SurfaceXCylinder type, extends(Surface) :: SurfaceYCylinder - ! (x - x0)^2 + (z - z0)^2 = R^2 - real(8) :: x0 - real(8) :: z0 - real(8) :: r end type SurfaceYCylinder type, extends(Surface) :: SurfaceZCylinder - ! (x - x0)^2 + (y - y0)^2 = R^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: r end type SurfaceZCylinder type, extends(Surface) :: SurfaceSphere - ! (x - x0)^2 + (y - y0)^2 + (z - z0)^2 = R^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r end type SurfaceSphere type, extends(Surface) :: SurfaceXCone - ! (y - y0)^2 + (z - z0)^2 = R^2*(x - x0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 end type SurfaceXCone type, extends(Surface) :: SurfaceYCone - ! (x - x0)^2 + (z - z0)^2 = R^2*(y - y0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 end type SurfaceYCone type, extends(Surface) :: SurfaceZCone - ! (x - x0)^2 + (y - y0)^2 = R^2*(z - z0)^2 - real(8) :: x0 - real(8) :: y0 - real(8) :: z0 - real(8) :: r2 end type SurfaceZCone type, extends(Surface) :: SurfaceQuadric - ! Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 - real(8) :: A, B, C, D, E, F, G, H, J, K end type SurfaceQuadric integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index 7684a36aa6..7c234f1735 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -4241,7 +4241,7 @@ contains real(C_DOUBLE) :: k_tra ! Copy of batch tracklength estimate of keff real(C_DOUBLE) :: val -#ifdef MPI +#ifdef OPENMC_MPI ! Combine tally results onto master process if (reduce_tallies) call reduce_tally_results() #endif @@ -4289,7 +4289,7 @@ contains ! REDUCE_TALLY_RESULTS collects all the results from tallies onto one processor !=============================================================================== -#ifdef MPI +#ifdef OPENMC_MPI subroutine reduce_tally_results() integer :: i diff --git a/src/tallies/trigger.F90 b/src/tallies/trigger.F90 index 9e9b06d205..ee2259ed48 100644 --- a/src/tallies/trigger.F90 +++ b/src/tallies/trigger.F90 @@ -2,7 +2,7 @@ module trigger use, intrinsic :: ISO_C_BINDING -#ifdef MPI +#ifdef OPENMC_MPI use message_passing #endif diff --git a/src/volume_calc.F90 b/src/volume_calc.F90 index 5985a236b3..07dc5b4184 100644 --- a/src/volume_calc.F90 +++ b/src/volume_calc.F90 @@ -136,7 +136,7 @@ contains integer :: total_hits ! total hits for a single domain (summed over materials) integer :: min_samples ! minimum number of samples per process integer :: remainder ! leftover samples from uneven divide -#ifdef MPI +#ifdef OPENMC_MPI integer :: mpi_err ! MPI error code integer :: m ! index over materials integer :: n ! number of materials @@ -279,7 +279,7 @@ contains total_hits = 0 if (master) then -#ifdef MPI +#ifdef OPENMC_MPI do j = 1, n_procs - 1 call MPI_RECV(n, 1, MPI_INTEGER, j, 0, mpi_intracomm, & MPI_STATUS_IGNORE, mpi_err) @@ -341,7 +341,7 @@ contains end do else -#ifdef MPI +#ifdef OPENMC_MPI n = master_indices(i_domain) % size() allocate(data(2*n)) do k = 0, n - 1 From 1f816bb919e960b9fb843595e813a27776311f65 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 23 Jan 2018 06:21:42 -0600 Subject: [PATCH 024/212] Raise CalledProcessError if openmc.run fails --- openmc/executor.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/openmc/executor.py b/openmc/executor.py index 51215e8b74..46ad53ec29 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -15,18 +15,22 @@ def _run(args, output, cwd): stderr=subprocess.STDOUT, universal_newlines=True) # Capture and re-print OpenMC output in real-time + lines = [] while True: # If OpenMC is finished, break loop line = p.stdout.readline() if not line and p.poll() is not None: break + lines.append(line) if output: # If user requested output, print to screen print(line, end='') - # Return the returncode (integer, zero if no problems encountered) - return p.returncode + # Raise an exception if return status is non-zero + if p.returncode != 0: + raise subprocess.CalledProcessError(p.returncode, ' '.join(args), + ''.join(lines)) def plot_geometry(output=True, openmc_exec='openmc', cwd='.'): @@ -42,7 +46,7 @@ def plot_geometry(output=True, openmc_exec='openmc', cwd='.'): Path to working directory to run in """ - return _run([openmc_exec, '-p'], output, cwd) + _run([openmc_exec, '-p'], output, cwd) def plot_inline(plots, openmc_exec='openmc', cwd='.', convert_exec='convert'): @@ -133,7 +137,7 @@ def calculate_volumes(threads=None, output=True, cwd='.', if mpi_args is not None: args = mpi_args + args - return _run(args, output, cwd) + _run(args, output, cwd) def run(particles=None, threads=None, geometry_debug=False, @@ -189,4 +193,4 @@ def run(particles=None, threads=None, geometry_debug=False, if mpi_args is not None: args = mpi_args + args - return _run(args, output, cwd) + _run(args, output, cwd) From 126cb65113f3b461dd2be9b2934b1d2293fffa9c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 23 Jan 2018 07:18:33 -0600 Subject: [PATCH 025/212] Don't check returncode in tests --- openmc/executor.py | 21 ++++++++++++++++++- tests/test_mg_convert/test_mg_convert.py | 7 ++----- .../test_mgxs_library_ce_to_mg.py | 13 ++++-------- tests/test_plot/test_plot.py | 3 +-- .../test_statepoint_restart.py | 10 +++------ tests/testing_harness.py | 16 +++++--------- 6 files changed, 35 insertions(+), 35 deletions(-) diff --git a/openmc/executor.py b/openmc/executor.py index 46ad53ec29..ada662a12f 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -45,6 +45,11 @@ def plot_geometry(output=True, openmc_exec='openmc', cwd='.'): cwd : str, optional Path to working directory to run in + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ _run([openmc_exec, '-p'], output, cwd) @@ -67,6 +72,11 @@ def plot_inline(plots, openmc_exec='openmc', cwd='.', convert_exec='convert'): convert_exec : str, optional Command that can convert PPM files into PNG files + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ from IPython.display import Image, display @@ -125,6 +135,11 @@ def calculate_volumes(threads=None, output=True, cwd='.', Path to working directory to run in. Defaults to the current working directory. + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + See Also -------- openmc.VolumeCalculation @@ -171,8 +186,12 @@ def run(particles=None, threads=None, geometry_debug=False, MPI execute command and any additional MPI arguments to pass, e.g. ['mpiexec', '-n', '8']. - """ + Raises + ------ + subprocess.CalledProcessError + If the `openmc` executable returns a non-zero status + """ args = [openmc_exec] if isinstance(particles, Integral) and particles > 0: diff --git a/tests/test_mg_convert/test_mg_convert.py b/tests/test_mg_convert/test_mg_convert.py index 9d13714580..36bfe5338b 100755 --- a/tests/test_mg_convert/test_mg_convert.py +++ b/tests/test_mg_convert/test_mg_convert.py @@ -139,13 +139,10 @@ class MGXSTestHarness(PyAPITestHarness): if self._opts.mpi_exec is not None: mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) - - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(openmc_exec=self._opts.exe) sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5') diff --git a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py b/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py index aaa83a70db..7ae47636e6 100644 --- a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py +++ b/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py @@ -36,13 +36,9 @@ class MGXSTestHarness(PyAPITestHarness): # Initial run if self._opts.mpi_exec is not None: mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) - - assert returncode == 0, 'CE OpenMC calculation did not exit' \ - 'successfully.' + openmc.run(openmc_exec=self._opts.exe) # Build MG Inputs # Get data needed to execute Library calculations. @@ -73,10 +69,9 @@ class MGXSTestHarness(PyAPITestHarness): # Re-run MG mode. if self._opts.mpi_exec is not None: mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(openmc_exec=self._opts.exe, - mpi_args=mpi_args) + openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=self._opts.exe) def _cleanup(self): super(MGXSTestHarness, self)._cleanup() diff --git a/tests/test_plot/test_plot.py b/tests/test_plot/test_plot.py index d484925cb4..1a99c24886 100644 --- a/tests/test_plot/test_plot.py +++ b/tests/test_plot/test_plot.py @@ -19,8 +19,7 @@ class PlotTestHarness(TestHarness): self._plot_names = plot_names def _run_openmc(self): - returncode = openmc.plot_geometry(openmc_exec=self._opts.exe) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.plot_geometry(openmc_exec=self._opts.exe) def _test_output_created(self): """Make sure *.ppm has been created.""" diff --git a/tests/test_statepoint_restart/test_statepoint_restart.py b/tests/test_statepoint_restart/test_statepoint_restart.py index 2c1c444958..9c10551dea 100644 --- a/tests/test_statepoint_restart/test_statepoint_restart.py +++ b/tests/test_statepoint_restart/test_statepoint_restart.py @@ -50,14 +50,10 @@ class StatepointRestartTestHarness(TestHarness): # Run OpenMC if self._opts.mpi_exec is not None: mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - returncode = openmc.run(restart_file=statepoint, - openmc_exec=self._opts.exe, - mpi_args=mpi_args) + openmc.run(restart_file=statepoint, openmc_exec=self._opts.exe, + mpi_args=mpi_args) else: - returncode = openmc.run(openmc_exec=self._opts.exe, - restart_file=statepoint) - - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(openmc_exec=self._opts.exe, restart_file=statepoint) if __name__ == '__main__': diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 428bf5c4b7..ad3b8ac1ec 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -62,14 +62,10 @@ class TestHarness(object): def _run_openmc(self): if self._opts.mpi_exec is not None: - returncode = openmc.run( - openmc_exec=self._opts.exe, - mpi_args=[self._opts.mpi_exec, '-n', self._opts.mpi_np]) - + openmc.run(openmc_exec=self._opts.exe, + mpi_args=[self._opts.mpi_exec, '-n', self._opts.mpi_np]) else: - returncode = openmc.run(openmc_exec=self._opts.exe) - - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(openmc_exec=self._opts.exe) def _test_output_created(self): """Make sure statepoint.* and tallies.out have been created.""" @@ -189,13 +185,11 @@ class ParticleRestartTestHarness(TestHarness): args['mpi_args'] = [self._opts.mpi_exec, '-n', self._opts.mpi_np] # Initial run - returncode = openmc.run(**args) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(**args) # Run particle restart args.update({'restart_file': self._sp_name}) - returncode = openmc.run(**args) - assert returncode == 0, 'OpenMC did not exit successfully.' + openmc.run(**args) def _test_output_created(self): """Make sure the restart file has been created.""" From 7624888df34577b9ed735039ff5b33bab8c0e44c Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 23 Jan 2018 12:37:28 -0500 Subject: [PATCH 026/212] Finish C++ surface->summary.h5 capability --- CMakeLists.txt | 1 + src/constants.F90 | 15 ++- src/error.F90 | 8 ++ src/error.h | 21 ++++ src/hdf5_interface.h | 44 +++++++- src/summary.F90 | 11 +- src/surface_header.C | 263 +++++++++++++++++++++++++++---------------- 7 files changed, 243 insertions(+), 120 deletions(-) create mode 100644 src/error.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 58fb55e799..e59713755f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -435,6 +435,7 @@ set(LIBOPENMC_FORTRAN_SRC src/tallies/trigger_header.F90 ) set(LIBOPENMC_CXX_SRC + src/error.h src/hdf5_interface.h src/random_lcg.h src/random_lcg.cpp diff --git a/src/constants.F90 b/src/constants.F90 index 331a644f09..3334a4cc76 100644 --- a/src/constants.F90 +++ b/src/constants.F90 @@ -43,9 +43,9 @@ module constants real(8), parameter :: TINY_BIT = 1e-8_8 ! User for precision in geometry - real(8), parameter :: FP_PRECISION = 1e-14_8 - real(8), parameter :: FP_REL_PRECISION = 1e-5_8 - real(8), parameter :: FP_COINCIDENT = 1e-12_8 + real(C_DOUBLE), bind(C, name='FP_PRECISION') :: FP_PRECISION = 1e-14_8 + real(C_DOUBLE), bind(C, name='FP_REL_PRECISION') :: FP_REL_PRECISION = 1e-5_8 + real(C_DOUBLE), bind(C, name='FP_COINCIDENT') :: FP_COINCIDENT = 1e-12_8 ! Maximum number of collisions/crossings integer, parameter :: MAX_EVENTS = 1000000 @@ -95,11 +95,10 @@ module constants ! GEOMETRY-RELATED CONSTANTS ! Boundary conditions - integer, parameter :: & - BC_TRANSMIT = 0, & ! Transmission boundary condition (default) - BC_VACUUM = 1, & ! Vacuum boundary condition - BC_REFLECT = 2, & ! Reflecting boundary condition - BC_PERIODIC = 3 ! Periodic boundary condition + integer(C_INT), bind(C, name="BC_TRANSMIT") :: BC_TRANSMIT + integer(C_INT), bind(C, name="BC_VACUUM") :: BC_VACUUM + integer(C_INT), bind(C, name="BC_REFLECT") :: BC_REFLECT + integer(C_INT), bind(C, name="BC_PERIODIC") :: BC_PERIODIC ! Logical operators for cell definitions integer, parameter :: & diff --git a/src/error.F90 b/src/error.F90 index ae02e0897d..cba1372917 100644 --- a/src/error.F90 +++ b/src/error.F90 @@ -194,6 +194,14 @@ contains end subroutine fatal_error + subroutine fatal_error_from_c(message, message_len) bind(C) + integer(C_INT), intent(in), value :: message_len + character(C_CHAR), intent(in) :: message(message_len) + character(message_len+1) :: message_out + write(message_out, *) message + call fatal_error(message_out) + end subroutine + !=============================================================================== ! WRITE_MESSAGE displays an informational message to the log file and the ! standard output stream. diff --git a/src/error.h b/src/error.h new file mode 100644 index 0000000000..77f0252e13 --- /dev/null +++ b/src/error.h @@ -0,0 +1,21 @@ +#ifndef ERROR_H +#define ERROR_H + +#include + + +extern "C" void fatal_error_from_c(const char *message, int message_len); + + +void fatal_error(const char *message) +{ + fatal_error_from_c(message, strlen(message)); +} + + +void fatal_error(const std::string &message) +{ + fatal_error_from_c(message.c_str(), message.length()); +} + +#endif // ERROR_H diff --git a/src/hdf5_interface.h b/src/hdf5_interface.h index 38bb7d88bc..2cded21f64 100644 --- a/src/hdf5_interface.h +++ b/src/hdf5_interface.h @@ -1,11 +1,44 @@ #ifndef HDF5_INTERFACE_H #define HDF5_INTERFACE_H -#include // For std::array -#include // For strlen +#include +#include #include "hdf5.h" +#include "error.h" + + +hid_t +create_group(hid_t parent_id, char const *name) +{ + hid_t out = H5Gcreate(parent_id, name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); + if (out < 0) { + std::string err_msg{"Failed to create HDF5 group \""}; + err_msg += name; + err_msg += "\""; + fatal_error(err_msg); + } + return out; +} + + +hid_t +create_group(hid_t parent_id, const std::string &name) +{ + return create_group(parent_id, name.c_str()); +} + + +void +close_group(hid_t group_id) +{ + herr_t err = H5Gclose(group_id); + if (err < 0) { + fatal_error("Failed to close HDF5 group"); + } +} + template void write_double_1D(hid_t group_id, char const *name, @@ -44,4 +77,11 @@ write_string(hid_t group_id, char const *name, char const *buffer) H5Dclose(dataset); } + +void +write_string(hid_t group_id, char const *name, const std::string &buffer) +{ + write_string(group_id, name, buffer.c_str()); +} + #endif //HDF5_INTERFACE_H diff --git a/src/summary.F90 b/src/summary.F90 index ca72764073..77bded9837 100644 --- a/src/summary.F90 +++ b/src/summary.F90 @@ -251,16 +251,7 @@ contains ! Write information on each surface SURFACE_LOOP: do i = 1, n_surfaces - s => surfaces(i)%obj - surface_group = create_group(surfaces_group, "surface " // & - trim(to_str(s%id))) - - call surface_to_hdf5_c(i-1, surface_group) - - ! Write name for this surface - call write_dataset(surface_group, "name", s%name) - - call close_group(surface_group) + call surface_to_hdf5_c(i-1, surfaces_group) end do SURFACE_LOOP call close_group(surfaces_group) diff --git a/src/surface_header.C b/src/surface_header.C index db53c8982e..4cfda86efa 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -1,3 +1,4 @@ +#include // for std::transform #include // For std::array #include // For strcmp #include // For numeric_limits @@ -6,23 +7,61 @@ #include "pugixml/pugixml.hpp" #include "hdf5.h" +#include "error.h" #include "hdf5_interface.h" // DEBUGGING #include #include +bool +check_for_node(const pugi::xml_node &node, const char *name) +{ + if (node.attribute(name)) { + return true; + } else if (node.child(name)) { + return true; + } else { + return false; + } +} + +std::string +get_node_value(const pugi::xml_node &node, const char *name) +{ + const pugi::char_t *value_char; + if (node.attribute(name)) { + value_char = node.attribute(name).value(); + } else if (node.child(name)) { + value_char = node.child_value(name); + } else { + std::string err_msg("Node \""); + err_msg += name; + err_msg += "\" is not a memeber of the \""; + err_msg += node.name(); + err_msg += "\" XML node"; + fatal_error(err_msg); + } + + std::string value(value_char); + std::transform(value.begin(), value.end(), value.begin(), ::tolower); + return value; +} + //============================================================================== // Constants //============================================================================== -const double FP_COINCIDENT = 1e-12; -const double INFTY = std::numeric_limits::max(); +//extern "C" const double FP_COINCIDENT{1e-12}; +//extern "C" const double INFTY{std::numeric_limits::max()}; +extern "C" double FP_COINCIDENT; +//extern "C" double INFTY; +const double INFTY{std::numeric_limits::max()}; -const int BC_TRANSMIT{0}; -const int BC_VACUUM{1}; -const int BC_REFLECT{2}; -const int BC_PERIODIC{3}; +extern "C" const int BC_TRANSMIT{0}; +extern "C" const int BC_VACUUM{1}; +extern "C" const int BC_REFLECT{2}; +extern "C" const int BC_PERIODIC{3}; //============================================================================== // Global array of surfaces @@ -95,12 +134,14 @@ class Surface { public: int id; //!< Unique ID - int neighbor_pos[], //!< List of cells on positive side - neighbor_neg[]; //!< List of cells on negative side + //int neighbor_pos[], //!< List of cells on positive side + // neighbor_neg[]; //!< List of cells on negative side int bc; //!< Boundary condition //TODO: switch that zero to a NONE constant. //int i_periodic = 0; //!< Index of corresponding periodic surface - char name[104]; //!< User-defined name + std::string name{""}; //!< User-defined name + + Surface(pugi::xml_node surf_node); //! Determine which side of a surface a point lies on. //! @param xyz[3] The 3D Cartesian coordinate of a point. @@ -139,12 +180,54 @@ public: //! Write all information needed to reconstruct the surface to an HDF5 group. //! @param group_id An HDF5 group id. - virtual void to_hdf5(hid_t group_id) const = 0; + void to_hdf5(hid_t group_id) const; protected: - void write_bc_to_hdf5(hid_t group_id) const; + virtual void to_hdf5_inner(hid_t group_id) const = 0; }; +Surface::Surface(pugi::xml_node surf_node) +{ + if (check_for_node(surf_node, "id")) { + id = stoi(get_node_value(surf_node, "id")); + } else { + fatal_error("Must specify id of surface in geometry XML file."); + } + //TODO: check for duplicate IDs + + if (check_for_node(surf_node, "name")) { + name = get_node_value(surf_node, "name"); + } + + if (check_for_node(surf_node, "boundary")) { + std::string surf_bc = get_node_value(surf_node, "boundary"); + + if (surf_bc.compare("transmission") == 0 + or surf_bc.compare("transmit") == 0 + or surf_bc.compare("") == 0) { + bc = BC_TRANSMIT; + + } else if (surf_bc.compare("vacuum") == 0) { + bc = BC_VACUUM; + + } else if (surf_bc.compare("reflective") == 0 + or surf_bc.compare("reflect") == 0 + or surf_bc.compare("reflecting") == 0) { + bc = BC_REFLECT; + } else if (surf_bc.compare("periodic") == 0) { + bc = BC_PERIODIC; + } else { + std::string err_msg("Unknown boundary condition \""); + err_msg += surf_bc + "\" specified on surface " + std::to_string(id); + fatal_error(err_msg); + } + + } else { + bc = BC_TRANSMIT; + } + +} + bool Surface::sense(const double xyz[3], const double uvw[3]) const { @@ -181,22 +264,35 @@ Surface::reflect(const double xyz[3], double uvw[3]) const } void -Surface::write_bc_to_hdf5(hid_t group_id) const +Surface::to_hdf5(hid_t group_id) const { + std::string group_name{"surface "}; + group_name += std::to_string(id); + + hid_t surf_group = create_group(group_id, group_name); + switch(bc) { case BC_TRANSMIT : - write_string(group_id, "boundary_type", "transmission"); + write_string(surf_group, "boundary_type", "transmission"); break; case BC_VACUUM : - write_string(group_id, "boundary_type", "vacuum"); + write_string(surf_group, "boundary_type", "vacuum"); break; case BC_REFLECT : - write_string(group_id, "boundary_type", "reflective"); + write_string(surf_group, "boundary_type", "reflective"); break; case BC_PERIODIC : - write_string(group_id, "boundary_type", "periodic"); + write_string(surf_group, "boundary_type", "periodic"); break; } + + if (name.compare("")) { + write_string(surf_group, "name", name); + } + + to_hdf5_inner(surf_group); + + close_group(surf_group); } //============================================================================== @@ -210,6 +306,8 @@ Surface::write_bc_to_hdf5(hid_t group_id) const class PeriodicSurface : public Surface { public: + PeriodicSurface(pugi::xml_node surf_node) : Surface(surf_node) {} + //! Translate a particle onto this surface from a periodic partner surface. //! @param other A pointer to the partner surface in this periodic BC. //! @param xyz[3] A point on the partner surface that will be translated onto @@ -271,12 +369,13 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) { read_coeffs(surf_node, x0); } @@ -297,12 +396,11 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<0, 1, 2>(xyz, uvw); } -void SurfaceXPlane::to_hdf5(hid_t group_id) const +void SurfaceXPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-plane"); std::array coeffs{{x0}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], @@ -347,12 +445,13 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) { read_coeffs(surf_node, y0); } @@ -373,12 +472,11 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<1, 0, 2>(xyz, uvw); } -void SurfaceYPlane::to_hdf5(hid_t group_id) const +void SurfaceYPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-plane"); std::array coeffs{{y0}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], @@ -423,12 +521,13 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) { read_coeffs(surf_node, z0); } @@ -449,12 +548,11 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const axis_aligned_plane_normal<2, 0, 1>(xyz, uvw); } -void SurfaceZPlane::to_hdf5(hid_t group_id) const +void SurfaceZPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-plane"); std::array coeffs{{z0}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], @@ -481,12 +579,13 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; }; SurfacePlane::SurfacePlane(pugi::xml_node surf_node) + : PeriodicSurface(surf_node) { read_coeffs(surf_node, A, B, C, D); } @@ -520,12 +619,11 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const uvw[2] = C; } -void SurfacePlane::to_hdf5(hid_t group_id) const +void SurfacePlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "plane"); std::array coeffs{{A, B, C, D}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], @@ -635,10 +733,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, y0, z0, r); } @@ -661,12 +760,11 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const } -void SurfaceXCylinder::to_hdf5(hid_t group_id) const +void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-cylinder"); std::array coeffs{{y0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -686,10 +784,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, z0, r); } @@ -711,12 +810,11 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const axis_aligned_cylinder_normal<1, 0, 2>(xyz, uvw, x0, z0); } -void SurfaceYCylinder::to_hdf5(hid_t group_id) const +void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-cylinder"); std::array coeffs{{x0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -736,10 +834,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, y0, r); } @@ -761,12 +860,11 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const axis_aligned_cylinder_normal<2, 0, 1>(xyz, uvw, x0, y0); } -void SurfaceZCylinder::to_hdf5(hid_t group_id) const +void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-cylinder"); std::array coeffs{{x0, y0, r}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -786,10 +884,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, y0, z0, r); } @@ -848,12 +947,11 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const uvw[2] = 2.0 * (xyz[2] - z0); } -void SurfaceSphere::to_hdf5(hid_t group_id) const +void SurfaceSphere::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "sphere"); std::array coeffs{{x0, y0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -956,10 +1054,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, y0, z0, r_sq); } @@ -981,12 +1080,11 @@ inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<0, 1, 2>(xyz, uvw, x0, y0, z0, r_sq); } -void SurfaceXCone::to_hdf5(hid_t group_id) const +void SurfaceXCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-cone"); std::array coeffs{{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -1006,10 +1104,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, y0, z0, r_sq); } @@ -1031,12 +1130,11 @@ inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<1, 0, 2>(xyz, uvw, y0, x0, z0, r_sq); } -void SurfaceYCone::to_hdf5(hid_t group_id) const +void SurfaceYCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-cone"); std::array coeffs{{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -1056,10 +1154,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, x0, y0, z0, r_sq); } @@ -1081,12 +1180,11 @@ inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const axis_aligned_cone_normal<2, 0, 1>(xyz, uvw, z0, x0, y0, r_sq); } -void SurfaceZCone::to_hdf5(hid_t group_id) const +void SurfaceZCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-cone"); std::array coeffs{{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -1106,10 +1204,11 @@ public: double distance(const double xyz[3], const double uvw[3], bool coincident) const; void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5(hid_t group_id) const; + void to_hdf5_inner(hid_t group_id) const; }; SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) + : Surface(surf_node) { read_coeffs(surf_node, A, B, C, D, E, F, G, H, J, K); } @@ -1191,12 +1290,11 @@ SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const uvw[2] = 2.0*C*z + E*y + F*x + J; } -void SurfaceQuadric::to_hdf5(hid_t group_id) const +void SurfaceQuadric::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "quadric"); std::array coeffs{{A, B, C, D, E, F, G, H, J, K}}; write_double_1D(group_id, "coefficients", coeffs); - write_bc_to_hdf5(group_id); } //============================================================================== @@ -1220,51 +1318,42 @@ read_surfaces(pugi::xml_node *node) int i_surf; for (surf_node = node->child("surface"), i_surf = 0; surf_node; surf_node = surf_node.next_sibling("surface"), i_surf++) { - const pugi::char_t *surf_type; - if (surf_node.attribute("type")) { - surf_type = surf_node.attribute("type").value(); - } else if (surf_node.child("type")) { - surf_type = surf_node.child_value("type"); - } else { - std::cout << "ERROR: Found a surface with no type attribute/node" - << std::endl; - //TODO: call fatal_error - } + std::string surf_type = get_node_value(surf_node, "type"); - if (strcmp(surf_type, "x-plane") == 0) { + if (surf_type.compare("x-plane") == 0) { surfaces_c[i_surf] = new SurfaceXPlane(surf_node); - } else if (strcmp(surf_type, "y-plane") == 0) { + } else if (surf_type.compare("y-plane") == 0) { surfaces_c[i_surf] = new SurfaceYPlane(surf_node); - } else if (strcmp(surf_type, "z-plane") == 0) { + } else if (surf_type.compare("z-plane") == 0) { surfaces_c[i_surf] = new SurfaceZPlane(surf_node); - } else if (strcmp(surf_type, "plane") == 0) { + } else if (surf_type.compare("plane") == 0) { surfaces_c[i_surf] = new SurfacePlane(surf_node); - } else if (strcmp(surf_type, "x-cylinder") == 0) { + } else if (surf_type.compare("x-cylinder") == 0) { surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); - } else if (strcmp(surf_type, "y-cylinder") == 0) { + } else if (surf_type.compare("y-cylinder") == 0) { surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); - } else if (strcmp(surf_type, "z-cylinder") == 0) { + } else if (surf_type.compare("z-cylinder") == 0) { surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); - } else if (strcmp(surf_type, "sphere") == 0) { + } else if (surf_type.compare("sphere") == 0) { surfaces_c[i_surf] = new SurfaceSphere(surf_node); - } else if (strcmp(surf_type, "x-cone") == 0) { + } else if (surf_type.compare("x-cone") == 0) { surfaces_c[i_surf] = new SurfaceXCone(surf_node); - } else if (strcmp(surf_type, "y-cone") == 0) { + } else if (surf_type.compare("y-cone") == 0) { surfaces_c[i_surf] = new SurfaceYCone(surf_node); - } else if (strcmp(surf_type, "z-cone") == 0) { + } else if (surf_type.compare("z-cone") == 0) { surfaces_c[i_surf] = new SurfaceZCone(surf_node); - } else if (strcmp(surf_type, "quadric") == 0) { + } else if (surf_type.compare("quadric") == 0) { surfaces_c[i_surf] = new SurfaceQuadric(surf_node); } else { @@ -1272,32 +1361,6 @@ read_surfaces(pugi::xml_node *node) std::cout << surf_type << std::endl; //TODO: call fatal_error } - - const pugi::char_t *surf_bc{""}; - if (surf_node.attribute("boundary")) { - surf_bc = surf_node.attribute("boundary").value(); - } else if (surf_node.child("boundary")) { - surf_bc = surf_node.attribute("boundary").value(); - } - - if (strcmp(surf_bc, "transmission") == 0 - or strcmp(surf_bc, "transmit") == 0 - or strcmp(surf_bc, "") == 0) { - surfaces_c[i_surf]->bc = BC_TRANSMIT; - - } else if (strcmp(surf_bc, "vacuum") == 0) { - surfaces_c[i_surf]->bc = BC_VACUUM; - - } else if (strcmp(surf_bc, "reflective") == 0 - or strcmp(surf_bc, "reflect") == 0 - or strcmp(surf_bc, "reflecting") == 0) { - surfaces_c[i_surf]->bc = BC_REFLECT; - } else if (strcmp(surf_bc, "periodic") == 0) { - surfaces_c[i_surf]->bc = BC_PERIODIC; - } else { - std::cout << "Unknown boundary condition" << std::endl; - //TODO: call fatal_error - } } } } From afe2f619c8dd855e9ff0503e4eb9af944b2fba3d Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 23 Jan 2018 15:21:21 -0500 Subject: [PATCH 027/212] Improve surface coeff error handling --- src/input_xml.F90 | 7 --- src/surface_header.C | 134 ++++++++++++++++++++++++++++++------------- 2 files changed, 95 insertions(+), 46 deletions(-) diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 462b9708f9..3f22522c2a 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -1068,13 +1068,6 @@ contains ! surface coordinates. n = node_word_count(node_surf, "coeffs") - if (n < coeffs_reqd) then - call fatal_error("Not enough coefficients specified for surface: " & - // trim(to_str(s%id))) - elseif (n > coeffs_reqd) then - call fatal_error("Too many coefficients specified for surface: " & - // trim(to_str(s%id))) - end if allocate(coeffs(n)) call get_node_array(node_surf, "coeffs", coeffs) diff --git a/src/surface_header.C b/src/surface_header.C index 4cfda86efa..565352623a 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -74,55 +74,111 @@ Surface **surfaces_c; // Helper functions for reading the "coeffs" node of an XML surface element //============================================================================== -const char* get_coeff_str(pugi::xml_node surf_node) +int word_count(const std::string &text) { - if (surf_node.attribute("coeffs")) { - return surf_node.attribute("coeffs").value(); - } else if (surf_node.child("coeffs")) { - return surf_node.child_value("coeffs"); - } else { - std::cout << "ERROR: Found a surface with no coefficients" << std::endl; - return nullptr; + bool in_word = false; + int count{0}; + for (auto c = text.begin(); c != text.end(); c++) { + switch(*c) { + case ' ' : + case '\t' : + case '\r' : + case '\n' : + if (in_word) { + in_word = false; + count++; + } + break; + default : + in_word = true; + } } + if (in_word) count++; + return count; } -void read_coeffs(pugi::xml_node surf_node, double &c1) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1) { - const char *coeffs = get_coeff_str(surf_node); - int stat = sscanf(coeffs, "%lf", &c1); + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 1) { + std::string err_msg{"Surface "}; + err_msg += std::to_string(surf_id); + err_msg += " expects 1 coeff but was given "; + err_msg += std::to_string(n_words); + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf", &c1); if (stat != 1) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; + fatal_error("Something went wrong reading surface coeffs"); } } -void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3) { - const char *coeffs = get_coeff_str(surf_node); - int stat = sscanf(coeffs, "%lf %lf %lf", &c1, &c2, &c3); + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 3) { + std::string err_msg{"Surface "}; + err_msg += std::to_string(surf_id); + err_msg += " expects 3 coeffs but was given "; + err_msg += std::to_string(n_words); + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf", &c1, &c2, &c3); if (stat != 3) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; + fatal_error("Something went wrong reading surface coeffs"); } } -void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, - double &c4) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3, double &c4) { - const char *coeffs = get_coeff_str(surf_node); - int stat = sscanf(coeffs, "%lf %lf %lf %lf", &c1, &c2, &c3, &c4); + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 4) { + std::string err_msg{"Surface "}; + err_msg += std::to_string(surf_id); + err_msg += " expects 4 coeffs but was given "; + err_msg += std::to_string(n_words); + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf %lf", &c1, &c2, &c3, &c4); if (stat != 4) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; + fatal_error("Something went wrong reading surface coeffs"); } } -void read_coeffs(pugi::xml_node surf_node, double &c1, double &c2, double &c3, - double &c4, double &c5, double &c6, double &c7, double &c8, - double &c9, double &c10) +void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, + double &c3, double &c4, double &c5, double &c6, double &c7, + double &c8, double &c9, double &c10) { - const char *coeffs = get_coeff_str(surf_node); - int stat = sscanf(coeffs, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", + // Check the given number of coefficients. + std::string coeffs = get_node_value(surf_node, "coeffs"); + int n_words = word_count(coeffs); + if (n_words != 10) { + std::string err_msg{"Surface "}; + err_msg += std::to_string(surf_id); + err_msg += " expects 10 coeffs but was given "; + err_msg += std::to_string(n_words); + fatal_error(err_msg); + } + + // Parse the coefficients. + int stat = sscanf(coeffs.c_str(), "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &c1, &c2, &c3, &c4, &c5, &c6, &c7, &c8, &c9, &c10); if (stat != 10) { - std::cout << "Something went wrong reading surface coeffs!" << std::endl; + fatal_error("Something went wrong reading surface coeffs"); } } @@ -377,7 +433,7 @@ public: SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { - read_coeffs(surf_node, x0); + read_coeffs(surf_node, id, x0); } inline double SurfaceXPlane::evaluate(const double xyz[3]) const @@ -453,7 +509,7 @@ public: SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { - read_coeffs(surf_node, y0); + read_coeffs(surf_node, id, y0); } inline double SurfaceYPlane::evaluate(const double xyz[3]) const @@ -529,7 +585,7 @@ public: SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { - read_coeffs(surf_node, z0); + read_coeffs(surf_node, id, z0); } inline double SurfaceZPlane::evaluate(const double xyz[3]) const @@ -587,7 +643,7 @@ public: SurfacePlane::SurfacePlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { - read_coeffs(surf_node, A, B, C, D); + read_coeffs(surf_node, id, A, B, C, D); } double @@ -739,7 +795,7 @@ public: SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, y0, z0, r); + read_coeffs(surf_node, id, y0, z0, r); } inline double SurfaceXCylinder::evaluate(const double xyz[3]) const @@ -790,7 +846,7 @@ public: SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, z0, r); + read_coeffs(surf_node, id, x0, z0, r); } inline double SurfaceYCylinder::evaluate(const double xyz[3]) const @@ -840,7 +896,7 @@ public: SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, y0, r); + read_coeffs(surf_node, id, x0, y0, r); } inline double SurfaceZCylinder::evaluate(const double xyz[3]) const @@ -890,7 +946,7 @@ public: SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, y0, z0, r); + read_coeffs(surf_node, id, x0, y0, z0, r); } double SurfaceSphere::evaluate(const double xyz[3]) const @@ -1060,7 +1116,7 @@ public: SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, y0, z0, r_sq); + read_coeffs(surf_node, id, x0, y0, z0, r_sq); } inline double SurfaceXCone::evaluate(const double xyz[3]) const @@ -1110,7 +1166,7 @@ public: SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, y0, z0, r_sq); + read_coeffs(surf_node, id, x0, y0, z0, r_sq); } inline double SurfaceYCone::evaluate(const double xyz[3]) const @@ -1160,7 +1216,7 @@ public: SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, x0, y0, z0, r_sq); + read_coeffs(surf_node, id, x0, y0, z0, r_sq); } inline double SurfaceZCone::evaluate(const double xyz[3]) const @@ -1210,7 +1266,7 @@ public: SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) : Surface(surf_node) { - read_coeffs(surf_node, A, B, C, D, E, F, G, H, J, K); + read_coeffs(surf_node, id, A, B, C, D, E, F, G, H, J, K); } double From 164e6c0ef4c7732a6245da2597fb6ff229deefe5 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 23 Jan 2018 18:29:05 -0500 Subject: [PATCH 028/212] Move more Surface implementation to C++ --- src/geometry.F90 | 20 ++- src/input_xml.F90 | 168 +--------------------- src/output.F90 | 2 +- src/summary.F90 | 5 +- src/surface_header.C | 201 +++++++++++++++++++++++++-- src/surface_header.F90 | 55 +------- src/tallies/tally_filter_surface.F90 | 2 +- src/tracking.F90 | 12 +- 8 files changed, 217 insertions(+), 248 deletions(-) diff --git a/src/geometry.F90 b/src/geometry.F90 index f1feb3ba30..d1519f8d21 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -54,16 +54,24 @@ module geometry real(C_DOUBLE), intent(out) :: uvw(3); end subroutine surface_normal_c - function surface_periodic_c(surf_ind1, surf_ind2, xyz, uvw) & + function surface_periodic_c(surf_ind1, xyz, uvw) & bind(C, name="surface_periodic") result(rotational) use ISO_C_BINDING implicit none integer(C_INT), intent(in), value :: surf_ind1; - integer(C_INT), intent(in), value :: surf_ind2; real(C_DOUBLE), intent(inout) :: xyz(3); real(C_DOUBLE), intent(inout) :: uvw(3); logical(C_BOOL) :: rotational end function surface_periodic_c + + function surface_i_periodic_c(surf_ind) bind(C, name="surface_i_periodic") & + result(i_periodic) + use ISO_C_BINDING + implicit none + integer(C_INT), intent(in), value :: surf_ind + integer(C_INT) :: i_periodic + end function + end interface contains @@ -857,15 +865,15 @@ contains ! Copy positive neighbors to Surface instance n = neighbor_pos(i)%size() if (n > 0) then - allocate(surfaces(i)%obj%neighbor_pos(n)) - surfaces(i)%obj%neighbor_pos(:) = neighbor_pos(i)%data(1:n) + allocate(surfaces(i)%neighbor_pos(n)) + surfaces(i)%neighbor_pos(:) = neighbor_pos(i)%data(1:n) end if ! Copy negative neighbors to Surface instance n = neighbor_neg(i)%size() if (n > 0) then - allocate(surfaces(i)%obj%neighbor_neg(n)) - surfaces(i)%obj%neighbor_neg(:) = neighbor_neg(i)%data(1:n) + allocate(surfaces(i)%neighbor_neg(n)) + surfaces(i)%neighbor_neg(:) = neighbor_neg(i)%data(1:n) end if end do diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 3f22522c2a..9b6e1c6fce 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -919,12 +919,8 @@ contains integer :: id integer :: univ_id integer :: n_cells_in_univ - integer :: coeffs_reqd - integer :: i_xmin, i_xmax, i_ymin, i_ymax, i_zmin, i_zmax - real(8) :: xmin, xmax, ymin, ymax, zmin, zmax integer, allocatable :: temp_int_array(:) real(8) :: phi, theta, psi - real(8), allocatable :: coeffs(:) logical :: file_exists logical :: boundary_exists character(MAX_LINE_LEN) :: filename @@ -984,13 +980,6 @@ contains call fatal_error("No surfaces found in geometry.xml!") end if - xmin = INFINITY - xmax = -INFINITY - ymin = INFINITY - ymax = -INFINITY - zmin = INFINITY - zmax = -INFINITY - ! Allocate cells array allocate(surfaces(n_surfaces)) @@ -998,52 +987,7 @@ contains ! Get pointer to i-th surface node node_surf = node_surf_list(i) - ! Copy and interpret surface type - word = '' - if (check_for_node(node_surf, "type")) & - call get_node_value(node_surf, "type", word) - select case(to_lower(word)) - case ('x-plane') - coeffs_reqd = 1 - allocate(SurfaceXPlane :: surfaces(i)%obj) - case ('y-plane') - coeffs_reqd = 1 - allocate(SurfaceYPlane :: surfaces(i)%obj) - case ('z-plane') - coeffs_reqd = 1 - allocate(SurfaceZPlane :: surfaces(i)%obj) - case ('plane') - coeffs_reqd = 4 - allocate(SurfacePlane :: surfaces(i)%obj) - case ('x-cylinder') - coeffs_reqd = 3 - allocate(SurfaceXCylinder :: surfaces(i)%obj) - case ('y-cylinder') - coeffs_reqd = 3 - allocate(SurfaceYCylinder :: surfaces(i)%obj) - case ('z-cylinder') - coeffs_reqd = 3 - allocate(SurfaceZCylinder :: surfaces(i)%obj) - case ('sphere') - coeffs_reqd = 4 - allocate(SurfaceSphere :: surfaces(i)%obj) - case ('x-cone') - coeffs_reqd = 4 - allocate(SurfaceXCone :: surfaces(i)%obj) - case ('y-cone') - coeffs_reqd = 4 - allocate(SurfaceYCone :: surfaces(i)%obj) - case ('z-cone') - coeffs_reqd = 4 - allocate(SurfaceZCone :: surfaces(i)%obj) - case ('quadric') - coeffs_reqd = 10 - allocate(SurfaceQuadric :: surfaces(i)%obj) - case default - call fatal_error("Invalid surface type: " // trim(word)) - end select - - s => surfaces(i)%obj + s => surfaces(i) ! Copy data into cells if (check_for_node(node_surf, "id")) then @@ -1058,44 +1002,10 @@ contains // to_str(s%id)) end if - ! Copy surface name - if (check_for_node(node_surf, "name")) then - call get_node_value(node_surf, "name", s%name) - end if - ! Check to make sure that the proper number of coefficients ! have been specified for the given type of surface. Then copy ! surface coordinates. - n = node_word_count(node_surf, "coeffs") - - allocate(coeffs(n)) - call get_node_array(node_surf, "coeffs", coeffs) - - select type(s) - type is (SurfaceXPlane) - ! Determine outer surfaces - xmin = min(xmin, coeffs(1)) - xmax = max(xmax, coeffs(1)) - if (xmin == coeffs(1)) i_xmin = i - if (xmax == coeffs(1)) i_xmax = i - type is (SurfaceYPlane) - ! Determine outer surfaces - ymin = min(ymin, coeffs(1)) - ymax = max(ymax, coeffs(1)) - if (ymin == coeffs(1)) i_ymin = i - if (ymax == coeffs(1)) i_ymax = i - type is (SurfaceZPlane) - ! Determine outer surfaces - zmin = min(zmin, coeffs(1)) - zmax = max(zmax, coeffs(1)) - if (zmin == coeffs(1)) i_zmin = i - if (zmax == coeffs(1)) i_zmax = i - end select - - ! No longer need coefficients - deallocate(coeffs) - ! Boundary conditions word = '' if (check_for_node(node_surf, "boundary")) & @@ -1112,12 +1022,6 @@ contains case ('periodic') s%bc = BC_PERIODIC boundary_exists = .true. - - ! Check for specification of periodic surface - if (check_for_node(node_surf, "periodic_surface_id")) then - call get_node_value(node_surf, "periodic_surface_id", & - s % i_periodic) - end if case default call fatal_error("Unknown boundary condition '" // trim(word) // & &"' specified on surface " // trim(to_str(s%id))) @@ -1134,76 +1038,6 @@ contains end if end if - ! Determine opposite side for periodic boundaries - do i = 1, size(surfaces) - if (surfaces(i) % obj % bc == BC_PERIODIC) then - select type (surf => surfaces(i) % obj) - type is (SurfaceXPlane) - if (surf % i_periodic == NONE) then - if (i == i_xmin) then - surf % i_periodic = i_xmax - elseif (i == i_xmax) then - surf % i_periodic = i_xmin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfaceYPlane) - if (surf % i_periodic == NONE) then - if (i == i_ymin) then - surf % i_periodic = i_ymax - elseif (i == i_ymax) then - surf % i_periodic = i_ymin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfaceZPlane) - if (surf % i_periodic == NONE) then - if (i == i_zmin) then - surf % i_periodic = i_zmax - elseif (i == i_zmax) then - surf % i_periodic = i_zmin - else - call fatal_error("Periodic boundary condition applied to & - &interior surface.") - end if - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - type is (SurfacePlane) - if (surf % i_periodic == NONE) then - call fatal_error("No matching periodic surface specified for & - &periodic boundary condition on surface " // & - trim(to_str(surf % id)) // ".") - else - surf % i_periodic = surface_dict % get(surf % i_periodic) - end if - - class default - call fatal_error("Periodic boundary condition applied to & - &non-planar surface.") - end select - - ! Make sure opposite surface is also periodic - associate (surf => surfaces(i) % obj) - if (surfaces(surf % i_periodic) % obj % bc /= BC_PERIODIC) then - call fatal_error("Could not find matching surface for periodic & - &boundary on surface " // trim(to_str(surf % id)) // ".") - end if - end associate - end if - end do - ! ========================================================================== ! READ CELLS FROM GEOMETRY.XML diff --git a/src/output.F90 b/src/output.F90 index 1b7cae121e..4113eea472 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -259,7 +259,7 @@ contains ! Print surface if (p % surface /= NONE) then - write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%obj%id, p % surface)) + write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%id, p % surface)) end if ! Display weight, energy, grid index, and interpolation factor diff --git a/src/summary.F90 b/src/summary.F90 index 77bded9837..9b82a03967 100644 --- a/src/summary.F90 +++ b/src/summary.F90 @@ -133,12 +133,11 @@ contains real(8), allocatable :: cell_temperatures(:) integer(HID_T) :: geom_group integer(HID_T) :: cells_group, cell_group - integer(HID_T) :: surfaces_group, surface_group + integer(HID_T) :: surfaces_group integer(HID_T) :: universes_group, univ_group integer(HID_T) :: lattices_group, lattice_group character(:), allocatable :: region_spec type(Cell), pointer :: c - class(Surface), pointer :: s class(Lattice), pointer :: lat ! Use H5LT interface to write number of geometry objects @@ -233,7 +232,7 @@ contains region_spec = trim(region_spec) // " |" case default region_spec = trim(region_spec) // " " // to_str(& - sign(surfaces(abs(k))%obj%id, k)) + sign(surfaces(abs(k))%id, k)) end select end do call write_dataset(cell_group, "region", adjustl(region_spec)) diff --git a/src/surface_header.C b/src/surface_header.C index 565352623a..afea2b43d3 100644 --- a/src/surface_header.C +++ b/src/surface_header.C @@ -1,7 +1,8 @@ #include // for std::transform -#include // For std::array +#include #include // For strcmp #include // For numeric_limits +#include #include // For fabs #include "pugixml/pugixml.hpp" @@ -45,6 +46,7 @@ get_node_value(const pugi::xml_node &node, const char *name) std::string value(value_char); std::transform(value.begin(), value.end(), value.begin(), ::tolower); + //TODO: trim whitespace return value; } @@ -57,6 +59,7 @@ get_node_value(const pugi::xml_node &node, const char *name) extern "C" double FP_COINCIDENT; //extern "C" double INFTY; const double INFTY{std::numeric_limits::max()}; +const int C_NONE{-1}; extern "C" const int BC_TRANSMIT{0}; extern "C" const int BC_VACUUM{1}; @@ -70,6 +73,8 @@ extern "C" const int BC_PERIODIC{3}; class Surface; Surface **surfaces_c; +std::map surface_dict; + //============================================================================== // Helper functions for reading the "coeffs" node of an XML surface element //============================================================================== @@ -182,6 +187,19 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, } } +//============================================================================== +//============================================================================== + +struct BoundingBox +{ + double xmin; + double xmax; + double ymin; + double ymax; + double zmin; + double zmax; +}; + //============================================================================== //! A geometry primitive used to define regions of 3D space. //============================================================================== @@ -193,8 +211,6 @@ public: //int neighbor_pos[], //!< List of cells on positive side // neighbor_neg[]; //!< List of cells on negative side int bc; //!< Boundary condition - //TODO: switch that zero to a NONE constant. - //int i_periodic = 0; //!< Index of corresponding periodic surface std::string name{""}; //!< User-defined name Surface(pugi::xml_node surf_node); @@ -249,7 +265,6 @@ Surface::Surface(pugi::xml_node surf_node) } else { fatal_error("Must specify id of surface in geometry XML file."); } - //TODO: check for duplicate IDs if (check_for_node(surf_node, "name")) { name = get_node_value(surf_node, "name"); @@ -362,7 +377,9 @@ Surface::to_hdf5(hid_t group_id) const class PeriodicSurface : public Surface { public: - PeriodicSurface(pugi::xml_node surf_node) : Surface(surf_node) {} + int i_periodic{C_NONE}; //!< Index of corresponding periodic surface + + PeriodicSurface(pugi::xml_node surf_node); //! Translate a particle onto this surface from a periodic partner surface. //! @param other A pointer to the partner surface in this periodic BC. @@ -374,8 +391,18 @@ public: //! boundary condition. virtual bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const = 0; + + virtual struct BoundingBox bounding_box() const = 0; }; +PeriodicSurface::PeriodicSurface(pugi::xml_node surf_node) + : Surface(surf_node) +{ + if (check_for_node(surf_node, "periodic_surface_id")) { + i_periodic = stoi(get_node_value(surf_node, "periodic_surface_id")); + } +} + //============================================================================== // Generic functions for x-, y-, and z-, planes. //============================================================================== @@ -428,6 +455,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; + struct BoundingBox bounding_box() const; }; SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) @@ -485,6 +513,13 @@ bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], } } +struct BoundingBox +SurfaceXPlane::bounding_box() const +{ + struct BoundingBox out{x0, x0, -INFTY, INFTY, -INFTY, INFTY}; + return out; +} + //============================================================================== // SurfaceYPlane //! A plane perpendicular to the y-axis. @@ -504,6 +539,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; + struct BoundingBox bounding_box() const; }; SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) @@ -561,6 +597,13 @@ bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], } } +struct BoundingBox +SurfaceYPlane::bounding_box() const +{ + struct BoundingBox out{-INFTY, INFTY, y0, y0, -INFTY, INFTY}; + return out; +} + //============================================================================== // SurfaceZPlane //! A plane perpendicular to the z-axis. @@ -580,6 +623,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; + struct BoundingBox bounding_box() const; }; SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) @@ -619,6 +663,13 @@ bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], return false; } +struct BoundingBox +SurfaceZPlane::bounding_box() const +{ + struct BoundingBox out{-INFTY, INFTY, -INFTY, INFTY, z0, z0}; + return out; +} + //============================================================================== // SurfacePlane //! A general plane. @@ -638,6 +689,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; + struct BoundingBox bounding_box() const; }; SurfacePlane::SurfacePlane(pugi::xml_node surf_node) @@ -698,6 +750,13 @@ bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], return false; } +struct BoundingBox +SurfacePlane::bounding_box() const +{ + struct BoundingBox out{-INFTY, INFTY, -INFTY, INFTY, -INFTY, INFTY}; + return out; +} + //============================================================================== // Generic functions for x-, y-, and z-, cylinders //============================================================================== @@ -1359,10 +1418,10 @@ extern "C" void read_surfaces(pugi::xml_node *node) { // Count the number of surfaces. - int n_surfaces = 0; + int n_surfaces{0}; for (pugi::xml_node surf_node = node->child("surface"); surf_node; surf_node = surf_node.next_sibling("surface")) { - n_surfaces += 1; + n_surfaces++; } // Allocate the array of Surface pointers. @@ -1413,12 +1472,125 @@ read_surfaces(pugi::xml_node *node) surfaces_c[i_surf] = new SurfaceQuadric(surf_node); } else { - std::cout << "Call error or handle uppercase here!" << std::endl; + std::cout << "Call error here!" << std::endl; std::cout << surf_type << std::endl; //TODO: call fatal_error } } } + + // Fill the surface dictionary. + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + int id = surfaces_c[i_surf]->id; + auto in_dict = surface_dict.find(id); + if (in_dict == surface_dict.end()) { + surface_dict[id] = i_surf; + } else { + std::string err_msg{"Two or more surfaces use the same unique ID: "}; + err_msg += std::to_string(id); + fatal_error(err_msg); + } + } + + // Find the global bounding box (of periodic BC surfaces). + double xmin{INFTY}, xmax{-INFTY}, ymin{INFTY}, ymax{-INFTY}, + zmin{INFTY}, zmax{-INFTY}; + int i_xmin, i_xmax, i_ymin, i_ymax, i_zmin, i_zmax; + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + if (surfaces_c[i_surf]->bc == BC_PERIODIC) { + // Downcast to the PeriodicSurface type. + Surface *surf_base = surfaces_c[i_surf]; + PeriodicSurface *surf = dynamic_cast(surf_base); + //TODO: check for null pointer + + // See if this surface makes part of the global bounding box. + struct BoundingBox bb = surf->bounding_box(); + if (bb.xmin > -INFTY and bb.xmin < xmin) { + xmin = bb.xmin; + i_xmin = i_surf; + } + if (bb.xmax < INFTY and bb.xmax > xmax) { + xmax = bb.xmax; + i_xmax = i_surf; + } + if (bb.ymin > -INFTY and bb.ymin < ymin) { + ymin = bb.ymin; + i_ymin = i_surf; + } + if (bb.ymax < INFTY and bb.ymax > ymax) { + ymax = bb.ymax; + i_ymax = i_surf; + } + if (bb.zmin > -INFTY and bb.zmin < zmin) { + zmin = bb.zmin; + i_zmin = i_surf; + } + if (bb.zmax < INFTY and bb.zmax > zmax) { + zmax = bb.zmax; + i_zmax = i_surf; + } + } + } + + // Set i_periodic for periodic BC surfaces. + for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { + if (surfaces_c[i_surf]->bc == BC_PERIODIC) { + // Downcast to the PeriodicSurface type. + Surface *surf_base = surfaces_c[i_surf]; + PeriodicSurface *surf = dynamic_cast(surf_base); + + // Also try downcasting to the SurfacePlane type (which must be handled + // differently). + SurfacePlane *surf_p = dynamic_cast(surf); + + if (surf_p == NULL) { + // This is not a SurfacePlane. + if (surf->i_periodic == C_NONE) { + // The user did not specify the matching periodic surface. See if we + // can find the partnered surface from the bounding box information. + if (i_surf == i_xmin) { + surf->i_periodic = i_xmax; + } else if (i_surf == i_xmax) { + surf->i_periodic = i_xmin; + } else if (i_surf == i_ymin) { + surf->i_periodic = i_ymax; + } else if (i_surf == i_ymax) { + surf->i_periodic = i_ymin; + } else if (i_surf == i_zmin) { + surf->i_periodic = i_zmax; + } else if (i_surf == i_zmax) { + surf->i_periodic = i_zmin; + } else { + fatal_error("Periodic boundary condition applied to interior " + "surface"); + } + } else { + // Convert the surface id to an index. + surf->i_periodic = surface_dict[surf->i_periodic]; + } + } else { + // This is a SurfacePlane. We won't try to find it's partner if the + // user didn't specify one. + if (surf->i_periodic == C_NONE) { + std::string err_msg{"No matching periodic surface specified for " + "periodic boundary condition on surface "}; + err_msg += std::to_string(surf->id); + fatal_error(err_msg); + } else { + // Convert the surface id to an index. + surf->i_periodic = surface_dict[surf->i_periodic]; + } + } + + // Make sure the opposite surface is also periodic. + if (surfaces_c[surf->i_periodic]->bc != BC_PERIODIC) { + std::string err_msg{"Could not find matching surface for periodic " + "boundary condition on surface "}; + err_msg += std::to_string(surf->id); + fatal_error(err_msg); + } + } + } } //============================================================================== @@ -1454,17 +1626,24 @@ surface_to_hdf5(int surf_ind, hid_t group) } extern "C" bool -surface_periodic(int surf_ind1, int surf_ind2, double xyz[3], double uvw[3]) +surface_periodic(int surf_ind1, double xyz[3], double uvw[3]) { - // Hopefully this function has only been called on a pair of surfaces that + // Hopefully this function has only been called for a pair of surfaces that // support periodic BCs (checking should have been done when reading the // geometry XML). Downcast the surfaces to the PeriodicSurface type so we // can call the periodic_translate method. Surface *surf1_gen = surfaces_c[surf_ind1]; PeriodicSurface *surf1 = dynamic_cast(surf1_gen); - Surface *surf2_gen = surfaces_c[surf_ind2]; + Surface *surf2_gen = surfaces_c[surf1->i_periodic]; PeriodicSurface *surf2 = dynamic_cast(surf2_gen); // Call the type-bound methods. return surf2->periodic_translate(surf1, xyz, uvw); } + +extern "C" int +surface_i_periodic(int surf_ind) +{ + PeriodicSurface *surf = dynamic_cast(surfaces_c[surf_ind]); + return surf->i_periodic; +} diff --git a/src/surface_header.F90 b/src/surface_header.F90 index 98e2423b62..ffe0a6db41 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -12,68 +12,17 @@ module surface_header ! construct closed volumes (cells) !=============================================================================== - type, abstract :: Surface + type :: Surface integer :: id ! Unique ID integer, allocatable :: & neighbor_pos(:), & ! List of cells on positive side neighbor_neg(:) ! List of cells on negative side integer :: bc ! Boundary condition - integer :: i_periodic = NONE ! Index of corresponding periodic surface - character(len=104) :: name = "" ! User-defined name end type Surface -!=============================================================================== -! SURFACECONTAINER allows us to store an array of different types of surfaces -!=============================================================================== - - type :: SurfaceContainer - class(Surface), allocatable :: obj - end type SurfaceContainer - -!=============================================================================== -! All the derived types below are extensions of the abstract Surface type. They -! inherent the reflect() type-bound procedure and must implement normal() -!=============================================================================== - - type, extends(Surface) :: SurfaceXPlane - end type SurfaceXPlane - - type, extends(Surface) :: SurfaceYPlane - end type SurfaceYPlane - - type, extends(Surface) :: SurfaceZPlane - end type SurfaceZPlane - - type, extends(Surface) :: SurfacePlane - end type SurfacePlane - - type, extends(Surface) :: SurfaceXCylinder - end type SurfaceXCylinder - - type, extends(Surface) :: SurfaceYCylinder - end type SurfaceYCylinder - - type, extends(Surface) :: SurfaceZCylinder - end type SurfaceZCylinder - - type, extends(Surface) :: SurfaceSphere - end type SurfaceSphere - - type, extends(Surface) :: SurfaceXCone - end type SurfaceXCone - - type, extends(Surface) :: SurfaceYCone - end type SurfaceYCone - - type, extends(Surface) :: SurfaceZCone - end type SurfaceZCone - - type, extends(Surface) :: SurfaceQuadric - end type SurfaceQuadric - integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces - type(SurfaceContainer), allocatable, target :: surfaces(:) + type(Surface), allocatable, target :: surfaces(:) ! Dictionary that maps user IDs to indices in 'surfaces' type(DictIntInt) :: surface_dict diff --git a/src/tallies/tally_filter_surface.F90 b/src/tallies/tally_filter_surface.F90 index daecd88917..6a2afa3ec6 100644 --- a/src/tallies/tally_filter_surface.F90 +++ b/src/tallies/tally_filter_surface.F90 @@ -105,7 +105,7 @@ contains integer, intent(in) :: bin character(MAX_LINE_LEN) :: label - label = "Surface " // to_str(surfaces(this % surfaces(bin)) % obj % id) + label = "Surface " // to_str(surfaces(this % surfaces(bin)) % id) end function text_label_surface end module tally_filter_surface diff --git a/src/tracking.F90 b/src/tracking.F90 index d616212ec6..98bca2a279 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -6,7 +6,7 @@ module tracking use geometry_header, only: cells use geometry, only: find_cell, distance_to_boundary, cross_lattice, & check_cell_overlap, surface_reflect_c, & - surface_periodic_c + surface_periodic_c, surface_i_periodic_c use message_passing use mgxs_header use nuclide_header @@ -298,7 +298,7 @@ contains class(Surface), pointer :: surf i_surface = abs(p % surface) - surf => surfaces(i_surface)%obj + surf => surfaces(i_surface) if (verbosity >= 10 .or. trace) then call write_message(" Crossing surface " // trim(to_str(surf % id))) end if @@ -412,14 +412,14 @@ contains p % coord(1) % xyz = xyz end if - rotational = surface_periodic_c(i_surface-1, surf % i_periodic-1, & - p % coord(1) % xyz, p % coord(1) % uvw) + rotational = surface_periodic_c(i_surface-1, p % coord(1) % xyz, & + p % coord(1) % uvw) ! Reassign particle's surface if (rotational) then - p % surface = surf % i_periodic + p % surface = surface_i_periodic_c(i_surface-1) + 1 else - p % surface = sign(surf % i_periodic, p % surface) + p % surface = sign(surface_i_periodic_c(i_surface-1) + 1, p % surface) end if ! Figure out what cell particle is in now From 983cbd48c65df2eb5578dd52d423caed915c26c2 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 23 Jan 2018 22:26:48 -0500 Subject: [PATCH 029/212] Clean up C++ surface file structure --- CMakeLists.txt | 10 +- src/error.h | 1 + src/{surface_header.C => surface.cpp} | 473 ++------------------------ src/surface.h | 431 +++++++++++++++++++++++ src/xml_interface.h | 52 +++ 5 files changed, 517 insertions(+), 450 deletions(-) rename src/{surface_header.C => surface.cpp} (72%) create mode 100644 src/surface.h create mode 100644 src/xml_interface.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e59713755f..625f001362 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -437,11 +437,13 @@ set(LIBOPENMC_FORTRAN_SRC set(LIBOPENMC_CXX_SRC src/error.h src/hdf5_interface.h - src/random_lcg.h src/random_lcg.cpp - src/surface_header.C - src/pugixml/pugixml.hpp - src/pugixml/pugixml.cpp) + src/random_lcg.h + src/surface.cpp + src/surface.h + src/xml_interface.h + src/pugixml/pugixml.cpp + src/pugixml/pugixml.hpp) add_library(libopenmc SHARED ${LIBOPENMC_FORTRAN_SRC} ${LIBOPENMC_CXX_SRC}) set_target_properties(libopenmc PROPERTIES OUTPUT_NAME openmc) add_executable(${program} src/main.F90) diff --git a/src/error.h b/src/error.h index 77f0252e13..0fd78a6c5c 100644 --- a/src/error.h +++ b/src/error.h @@ -1,6 +1,7 @@ #ifndef ERROR_H #define ERROR_H +#include #include diff --git a/src/surface_header.C b/src/surface.cpp similarity index 72% rename from src/surface_header.C rename to src/surface.cpp index afea2b43d3..ed111b0370 100644 --- a/src/surface_header.C +++ b/src/surface.cpp @@ -1,79 +1,11 @@ -#include // for std::transform #include -#include // For strcmp -#include // For numeric_limits -#include #include // For fabs -#include "pugixml/pugixml.hpp" -#include "hdf5.h" - #include "error.h" #include "hdf5_interface.h" +#include "xml_interface.h" -// DEBUGGING -#include -#include - -bool -check_for_node(const pugi::xml_node &node, const char *name) -{ - if (node.attribute(name)) { - return true; - } else if (node.child(name)) { - return true; - } else { - return false; - } -} - -std::string -get_node_value(const pugi::xml_node &node, const char *name) -{ - const pugi::char_t *value_char; - if (node.attribute(name)) { - value_char = node.attribute(name).value(); - } else if (node.child(name)) { - value_char = node.child_value(name); - } else { - std::string err_msg("Node \""); - err_msg += name; - err_msg += "\" is not a memeber of the \""; - err_msg += node.name(); - err_msg += "\" XML node"; - fatal_error(err_msg); - } - - std::string value(value_char); - std::transform(value.begin(), value.end(), value.begin(), ::tolower); - //TODO: trim whitespace - return value; -} - -//============================================================================== -// Constants -//============================================================================== - -//extern "C" const double FP_COINCIDENT{1e-12}; -//extern "C" const double INFTY{std::numeric_limits::max()}; -extern "C" double FP_COINCIDENT; -//extern "C" double INFTY; -const double INFTY{std::numeric_limits::max()}; -const int C_NONE{-1}; - -extern "C" const int BC_TRANSMIT{0}; -extern "C" const int BC_VACUUM{1}; -extern "C" const int BC_REFLECT{2}; -extern "C" const int BC_PERIODIC{3}; - -//============================================================================== -// Global array of surfaces -//============================================================================== - -class Surface; -Surface **surfaces_c; - -std::map surface_dict; +#include "surface.h" //============================================================================== // Helper functions for reading the "coeffs" node of an XML surface element @@ -84,18 +16,13 @@ int word_count(const std::string &text) bool in_word = false; int count{0}; for (auto c = text.begin(); c != text.end(); c++) { - switch(*c) { - case ' ' : - case '\t' : - case '\r' : - case '\n' : - if (in_word) { - in_word = false; - count++; - } - break; - default : - in_word = true; + if (std::isspace(*c)) { + if (in_word) { + in_word = false; + count++; + } + } else { + in_word = true; } } if (in_word) count++; @@ -188,76 +115,9 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, } //============================================================================== +// Surface implementation //============================================================================== -struct BoundingBox -{ - double xmin; - double xmax; - double ymin; - double ymax; - double zmin; - double zmax; -}; - -//============================================================================== -//! A geometry primitive used to define regions of 3D space. -//============================================================================== - -class Surface -{ -public: - int id; //!< Unique ID - //int neighbor_pos[], //!< List of cells on positive side - // neighbor_neg[]; //!< List of cells on negative side - int bc; //!< Boundary condition - std::string name{""}; //!< User-defined name - - Surface(pugi::xml_node surf_node); - - //! Determine which side of a surface a point lies on. - //! @param xyz[3] The 3D Cartesian coordinate of a point. - //! @param uvw[3] A direction used to "break ties" and pick a sense when the - //! point is very close to the surface. - //! @return true if the point is on the "positive" side of the surface and - //! false otherwise. - bool sense(const double xyz[3], const double uvw[3]) const; - - //! Determine the direction of a ray reflected from the surface. - //! @param xyz[3] The point at which the ray is incident. - //! @param uvw[3] A direction. This is both an input and an output parameter. - //! It specifies the icident direction on input and the reflected direction - //! on output. - void reflect(const double xyz[3], double uvw[3]) const; - - //! Evaluate the equation describing the surface. - //! - //! Surfaces can be described by some function f(x, y, z) = 0. This member - //! function evaluates that mathematical function. - //! @param xyz[3] A 3D Cartesian coordinate. - virtual double evaluate(const double xyz[3]) const = 0; - - //! Compute the distance between a point and the surface along a ray. - //! @param xyz[3] A 3D Cartesian coordinate. - //! @param uvw[3] The direction of the ray. - //! @param coincident A hint to the code that the given point should lie - //! exactly on the surface. - virtual double distance(const double xyz[3], const double uvw[3], - bool coincident) const = 0; - - //! Compute the local outward normal direction of the surface. - //! @param xyz[3] A 3D Cartesian coordinate. - //! @param uvw[3] This output argument provides the normal. - virtual void normal(const double xyz[3], double uvw[3]) const = 0; - - //! Write all information needed to reconstruct the surface to an HDF5 group. - //! @param group_id An HDF5 group id. - void to_hdf5(hid_t group_id) const; - -protected: - virtual void to_hdf5_inner(hid_t group_id) const = 0; -}; - Surface::Surface(pugi::xml_node surf_node) { if (check_for_node(surf_node, "id")) { @@ -367,34 +227,9 @@ Surface::to_hdf5(hid_t group_id) const } //============================================================================== -//! A `Surface` that supports periodic boundary conditions. -//! -//! Translational periodicity is supported for the `XPlane`, `YPlane`, `ZPlane`, -//! and `Plane` types. Rotational periodicity is supported for -//! `XPlane`-`YPlane` pairs. +// PeriodicSurface implementation //============================================================================== -class PeriodicSurface : public Surface -{ -public: - int i_periodic{C_NONE}; //!< Index of corresponding periodic surface - - PeriodicSurface(pugi::xml_node surf_node); - - //! Translate a particle onto this surface from a periodic partner surface. - //! @param other A pointer to the partner surface in this periodic BC. - //! @param xyz[3] A point on the partner surface that will be translated onto - //! this surface. - //! @param uvw[3] A direction that will be rotated for systems with rotational - //! periodicity. - //! @return true if this surface and its partner make a rotationally-periodic - //! boundary condition. - virtual bool periodic_translate(PeriodicSurface *other, double xyz[3], - double uvw[3]) const = 0; - - virtual struct BoundingBox bounding_box() const = 0; -}; - PeriodicSurface::PeriodicSurface(pugi::xml_node surf_node) : Surface(surf_node) { @@ -437,27 +272,9 @@ axis_aligned_plane_normal(const double xyz[3], double uvw[3]) } //============================================================================== -// SurfaceXPlane -//! A plane perpendicular to the x-axis. -// -//! The plane is described by the equation \f$x - x_0 = 0\f$ +// SurfaceXPlane implementation //============================================================================== -class SurfaceXPlane : public PeriodicSurface -{ - double x0; -public: - SurfaceXPlane(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], bool coincident) - const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; - bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) - const; - struct BoundingBox bounding_box() const; -}; - SurfaceXPlane::SurfaceXPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { @@ -521,27 +338,9 @@ SurfaceXPlane::bounding_box() const } //============================================================================== -// SurfaceYPlane -//! A plane perpendicular to the y-axis. -// -//! The plane is described by the equation \f$y - y_0 = 0\f$ +// SurfaceYPlane implementation //============================================================================== -class SurfaceYPlane : public PeriodicSurface -{ - double y0; -public: - SurfaceYPlane(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; - bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) - const; - struct BoundingBox bounding_box() const; -}; - SurfaceYPlane::SurfaceYPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { @@ -605,27 +404,9 @@ SurfaceYPlane::bounding_box() const } //============================================================================== -// SurfaceZPlane -//! A plane perpendicular to the z-axis. -// -//! The plane is described by the equation \f$z - z_0 = 0\f$ +// SurfaceZPlane implementation //============================================================================== -class SurfaceZPlane : public PeriodicSurface -{ - double z0; -public: - SurfaceZPlane(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; - bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) - const; - struct BoundingBox bounding_box() const; -}; - SurfaceZPlane::SurfaceZPlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { @@ -671,27 +452,9 @@ SurfaceZPlane::bounding_box() const } //============================================================================== -// SurfacePlane -//! A general plane. -// -//! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ +// SurfacePlane implementation //============================================================================== -class SurfacePlane : public PeriodicSurface -{ - double A, B, C, D; -public: - SurfacePlane(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], bool coincident) - const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; - bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) - const; - struct BoundingBox bounding_box() const; -}; - SurfacePlane::SurfacePlane(pugi::xml_node surf_node) : PeriodicSurface(surf_node) { @@ -832,25 +595,9 @@ axis_aligned_cylinder_normal(const double xyz[3], double uvw[3], double offset1, } //============================================================================== -// SurfaceXCylinder -//! A cylinder aligned along the x-axis. -// -//! The cylinder is described by the equation -//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +// SurfaceXCylinder implementation //============================================================================== -class SurfaceXCylinder : public Surface -{ - double y0, z0, r; -public: - SurfaceXCylinder(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceXCylinder::SurfaceXCylinder(pugi::xml_node surf_node) : Surface(surf_node) { @@ -883,25 +630,9 @@ void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceYCylinder -//! A cylinder aligned along the y-axis. -// -//! The cylinder is described by the equation -//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +// SurfaceYCylinder implementation //============================================================================== -class SurfaceYCylinder : public Surface -{ - double x0, z0, r; -public: - SurfaceYCylinder(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceYCylinder::SurfaceYCylinder(pugi::xml_node surf_node) : Surface(surf_node) { @@ -933,25 +664,9 @@ void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceZCylinder -//! A cylinder aligned along the z-axis. -// -//! The cylinder is described by the equation -//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ +// SurfaceZCylinder implementation //============================================================================== -class SurfaceZCylinder : public Surface -{ - double x0, y0, r; -public: - SurfaceZCylinder(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceZCylinder::SurfaceZCylinder(pugi::xml_node surf_node) : Surface(surf_node) { @@ -983,25 +698,9 @@ void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceSphere -//! A sphere. -// -//! The cylinder is described by the equation -//! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +// SurfaceSphere implementation //============================================================================== -class SurfaceSphere : public Surface -{ - double x0, y0, z0, r; -public: - SurfaceSphere(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceSphere::SurfaceSphere(pugi::xml_node surf_node) : Surface(surf_node) { @@ -1153,25 +852,9 @@ axis_aligned_cone_normal(const double xyz[3], double uvw[3], double offset1, } //============================================================================== -// SurfaceXCone -//! A cone aligned along the x-axis. -// -//! The cylinder is described by the equation -//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ +// SurfaceXCone implementation //============================================================================== -class SurfaceXCone : public Surface -{ - double x0, y0, z0, r_sq; -public: - SurfaceXCone(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceXCone::SurfaceXCone(pugi::xml_node surf_node) : Surface(surf_node) { @@ -1203,25 +886,9 @@ void SurfaceXCone::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceYCone -//! A cone aligned along the y-axis. -// -//! The cylinder is described by the equation -//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ +// SurfaceYCone implementation //============================================================================== -class SurfaceYCone : public Surface -{ - double x0, y0, z0, r_sq; -public: - SurfaceYCone(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceYCone::SurfaceYCone(pugi::xml_node surf_node) : Surface(surf_node) { @@ -1253,25 +920,9 @@ void SurfaceYCone::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceZCone -//! A cone aligned along the z-axis. -// -//! The cylinder is described by the equation -//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ +// SurfaceZCone implementation //============================================================================== -class SurfaceZCone : public Surface -{ - double x0, y0, z0, r_sq; -public: - SurfaceZCone(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceZCone::SurfaceZCone(pugi::xml_node surf_node) : Surface(surf_node) { @@ -1303,25 +954,9 @@ void SurfaceZCone::to_hdf5_inner(hid_t group_id) const } //============================================================================== -// SurfaceQuadric -//! A general surface described by a quadratic equation. -// -//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ +// SurfaceQuadric implementation //============================================================================== -class SurfaceQuadric : public Surface -{ - // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 - double A, B, C, D, E, F, G, H, J, K; -public: - SurfaceQuadric(pugi::xml_node surf_node); - double evaluate(const double xyz[3]) const; - double distance(const double xyz[3], const double uvw[3], - bool coincident) const; - void normal(const double xyz[3], double uvw[3]) const; - void to_hdf5_inner(hid_t group_id) const; -}; - SurfaceQuadric::SurfaceQuadric(pugi::xml_node surf_node) : Surface(surf_node) { @@ -1472,9 +1107,10 @@ read_surfaces(pugi::xml_node *node) surfaces_c[i_surf] = new SurfaceQuadric(surf_node); } else { - std::cout << "Call error here!" << std::endl; - std::cout << surf_type << std::endl; - //TODO: call fatal_error + std::string err_msg{"Invalid surface type, \""}; + err_msg += surf_type; + err_msg += "\""; + fatal_error(err_msg); } } } @@ -1592,58 +1228,3 @@ read_surfaces(pugi::xml_node *node) } } } - -//============================================================================== - -extern "C" bool -surface_sense(int surf_ind, double xyz[3], double uvw[3]) -{ - return surfaces_c[surf_ind]->sense(xyz, uvw); -} - -extern "C" void -surface_reflect(int surf_ind, double xyz[3], double uvw[3]) -{ - surfaces_c[surf_ind]->reflect(xyz, uvw); -} - -extern "C" double -surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) -{ - return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); -} - -extern "C" void -surface_normal(int surf_ind, double xyz[3], double uvw[3]) -{ - return surfaces_c[surf_ind]->normal(xyz, uvw); -} - -extern "C" void -surface_to_hdf5(int surf_ind, hid_t group) -{ - surfaces_c[surf_ind]->to_hdf5(group); -} - -extern "C" bool -surface_periodic(int surf_ind1, double xyz[3], double uvw[3]) -{ - // Hopefully this function has only been called for a pair of surfaces that - // support periodic BCs (checking should have been done when reading the - // geometry XML). Downcast the surfaces to the PeriodicSurface type so we - // can call the periodic_translate method. - Surface *surf1_gen = surfaces_c[surf_ind1]; - PeriodicSurface *surf1 = dynamic_cast(surf1_gen); - Surface *surf2_gen = surfaces_c[surf1->i_periodic]; - PeriodicSurface *surf2 = dynamic_cast(surf2_gen); - - // Call the type-bound methods. - return surf2->periodic_translate(surf1, xyz, uvw); -} - -extern "C" int -surface_i_periodic(int surf_ind) -{ - PeriodicSurface *surf = dynamic_cast(surfaces_c[surf_ind]); - return surf->i_periodic; -} diff --git a/src/surface.h b/src/surface.h new file mode 100644 index 0000000000..22eb798dcb --- /dev/null +++ b/src/surface.h @@ -0,0 +1,431 @@ +#ifndef SURFACE_H +#define SURFACE_H + +#include +#include // For numeric_limits + +#include "hdf5.h" +#include "pugixml/pugixml.hpp" + +//============================================================================== +// Module constants +//============================================================================== + +extern "C" const int BC_TRANSMIT{0}; +extern "C" const int BC_VACUUM{1}; +extern "C" const int BC_REFLECT{2}; +extern "C" const int BC_PERIODIC{3}; + +//============================================================================== +// Constants that should eventually be moved out of this file +//============================================================================== + +extern "C" double FP_COINCIDENT; +const double INFTY{std::numeric_limits::max()}; +const int C_NONE{-1}; + +//============================================================================== +// Global variables +//============================================================================== + +class Surface; +Surface **surfaces_c; + +std::map surface_dict; + +//============================================================================== +//! Coordinates for an axis-aligned cube that bounds a geometric object. +//============================================================================== + +struct BoundingBox +{ + double xmin; + double xmax; + double ymin; + double ymax; + double zmin; + double zmax; +}; + +//============================================================================== +//! A geometry primitive used to define regions of 3D space. +//============================================================================== + +class Surface +{ +public: + int id; //!< Unique ID + //int neighbor_pos[], //!< List of cells on positive side + // neighbor_neg[]; //!< List of cells on negative side + int bc; //!< Boundary condition + std::string name{""}; //!< User-defined name + + Surface(pugi::xml_node surf_node); + + //! Determine which side of a surface a point lies on. + //! @param xyz[3] The 3D Cartesian coordinate of a point. + //! @param uvw[3] A direction used to "break ties" and pick a sense when the + //! point is very close to the surface. + //! @return true if the point is on the "positive" side of the surface and + //! false otherwise. + bool sense(const double xyz[3], const double uvw[3]) const; + + //! Determine the direction of a ray reflected from the surface. + //! @param xyz[3] The point at which the ray is incident. + //! @param uvw[3] A direction. This is both an input and an output parameter. + //! It specifies the icident direction on input and the reflected direction + //! on output. + void reflect(const double xyz[3], double uvw[3]) const; + + //! Evaluate the equation describing the surface. + //! + //! Surfaces can be described by some function f(x, y, z) = 0. This member + //! function evaluates that mathematical function. + //! @param xyz[3] A 3D Cartesian coordinate. + virtual double evaluate(const double xyz[3]) const = 0; + + //! Compute the distance between a point and the surface along a ray. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] The direction of the ray. + //! @param coincident A hint to the code that the given point should lie + //! exactly on the surface. + virtual double distance(const double xyz[3], const double uvw[3], + bool coincident) const = 0; + + //! Compute the local outward normal direction of the surface. + //! @param xyz[3] A 3D Cartesian coordinate. + //! @param uvw[3] This output argument provides the normal. + virtual void normal(const double xyz[3], double uvw[3]) const = 0; + + //! Write all information needed to reconstruct the surface to an HDF5 group. + //! @param group_id An HDF5 group id. + void to_hdf5(hid_t group_id) const; + +protected: + virtual void to_hdf5_inner(hid_t group_id) const = 0; +}; + +//============================================================================== +//! A `Surface` that supports periodic boundary conditions. +//! +//! Translational periodicity is supported for the `XPlane`, `YPlane`, `ZPlane`, +//! and `Plane` types. Rotational periodicity is supported for +//! `XPlane`-`YPlane` pairs. +//============================================================================== + +class PeriodicSurface : public Surface +{ +public: + int i_periodic{C_NONE}; //!< Index of corresponding periodic surface + + PeriodicSurface(pugi::xml_node surf_node); + + //! Translate a particle onto this surface from a periodic partner surface. + //! @param other A pointer to the partner surface in this periodic BC. + //! @param xyz[3] A point on the partner surface that will be translated onto + //! this surface. + //! @param uvw[3] A direction that will be rotated for systems with rotational + //! periodicity. + //! @return true if this surface and its partner make a rotationally-periodic + //! boundary condition. + virtual bool periodic_translate(PeriodicSurface *other, double xyz[3], + double uvw[3]) const = 0; + + //! Get the bounding box for this surface. + virtual struct BoundingBox bounding_box() const = 0; +}; + +//============================================================================== +//! A plane perpendicular to the x-axis. +// +//! The plane is described by the equation \f$x - x_0 = 0\f$ +//============================================================================== + +class SurfaceXPlane : public PeriodicSurface +{ + double x0; +public: + SurfaceXPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + struct BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A plane perpendicular to the y-axis. +// +//! The plane is described by the equation \f$y - y_0 = 0\f$ +//============================================================================== + +class SurfaceYPlane : public PeriodicSurface +{ + double y0; +public: + SurfaceYPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + struct BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A plane perpendicular to the z-axis. +// +//! The plane is described by the equation \f$z - z_0 = 0\f$ +//============================================================================== + +class SurfaceZPlane : public PeriodicSurface +{ + double z0; +public: + SurfaceZPlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + struct BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A general plane. +// +//! The plane is described by the equation \f$A x + B y + C z - D = 0\f$ +//============================================================================== + +class SurfacePlane : public PeriodicSurface +{ + double A, B, C, D; +public: + SurfacePlane(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], bool coincident) + const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; + bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) + const; + struct BoundingBox bounding_box() const; +}; + +//============================================================================== +//! A cylinder aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceXCylinder : public Surface +{ + double y0, z0, r; +public: + SurfaceXCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cylinder aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceYCylinder : public Surface +{ + double x0, z0, r; +public: + SurfaceYCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cylinder aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceZCylinder : public Surface +{ + double x0, y0, r; +public: + SurfaceZCylinder(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A sphere. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 + (z - z_0)^2 - R^2 = 0\f$ +//============================================================================== + +class SurfaceSphere : public Surface +{ + double x0, y0, z0, r; +public: + SurfaceSphere(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the x-axis. +// +//! The cylinder is described by the equation +//! \f$(y - y_0)^2 + (z - z_0)^2 - R^2 (x - x_0)^2 = 0\f$ +//============================================================================== + +class SurfaceXCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + SurfaceXCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the y-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (z - z_0)^2 - R^2 (y - y_0)^2 = 0\f$ +//============================================================================== + +class SurfaceYCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + SurfaceYCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A cone aligned along the z-axis. +// +//! The cylinder is described by the equation +//! \f$(x - x_0)^2 + (y - y_0)^2 - R^2 (z - z_0)^2 = 0\f$ +//============================================================================== + +class SurfaceZCone : public Surface +{ + double x0, y0, z0, r_sq; +public: + SurfaceZCone(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +//! A general surface described by a quadratic equation. +// +//! \f$A x^2 + B y^2 + C z^2 + D x y + E y z + F x z + G x + H y + J z + K = 0\f$ +//============================================================================== + +class SurfaceQuadric : public Surface +{ + // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 + double A, B, C, D, E, F, G, H, J, K; +public: + SurfaceQuadric(pugi::xml_node surf_node); + double evaluate(const double xyz[3]) const; + double distance(const double xyz[3], const double uvw[3], + bool coincident) const; + void normal(const double xyz[3], double uvw[3]) const; + void to_hdf5_inner(hid_t group_id) const; +}; + +//============================================================================== +// Fortran compatibility functions +//============================================================================== + +extern "C" bool +surface_sense(int surf_ind, double xyz[3], double uvw[3]) +{ + return surfaces_c[surf_ind]->sense(xyz, uvw); +} + +extern "C" void +surface_reflect(int surf_ind, double xyz[3], double uvw[3]) +{ + surfaces_c[surf_ind]->reflect(xyz, uvw); +} + +extern "C" double +surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) +{ + return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); +} + +extern "C" void +surface_normal(int surf_ind, double xyz[3], double uvw[3]) +{ + return surfaces_c[surf_ind]->normal(xyz, uvw); +} + +extern "C" void +surface_to_hdf5(int surf_ind, hid_t group) +{ + surfaces_c[surf_ind]->to_hdf5(group); +} + +extern "C" bool +surface_periodic(int surf_ind1, double xyz[3], double uvw[3]) +{ + // Hopefully this function has only been called for a pair of surfaces that + // support periodic BCs (checking should have been done when reading the + // geometry XML). Downcast the surfaces to the PeriodicSurface type so we + // can call the periodic_translate method. + Surface *surf1_gen = surfaces_c[surf_ind1]; + PeriodicSurface *surf1 = dynamic_cast(surf1_gen); + Surface *surf2_gen = surfaces_c[surf1->i_periodic]; + PeriodicSurface *surf2 = dynamic_cast(surf2_gen); + + // Call the type-bound methods. + return surf2->periodic_translate(surf1, xyz, uvw); +} + +extern "C" int +surface_i_periodic(int surf_ind) +{ + PeriodicSurface *surf = dynamic_cast(surfaces_c[surf_ind]); + return surf->i_periodic; +} + +#endif // SURFACE_H diff --git a/src/xml_interface.h b/src/xml_interface.h new file mode 100644 index 0000000000..fbc82e056b --- /dev/null +++ b/src/xml_interface.h @@ -0,0 +1,52 @@ +#ifndef XML_INTERFACE_H +#define XML_INTERFACE_H + +#include // for std::transform +#include + +#include "pugixml/pugixml.hpp" + + +bool +check_for_node(const pugi::xml_node &node, const char *name) +{ + if (node.attribute(name)) { + return true; + } else if (node.child(name)) { + return true; + } else { + return false; + } +} + + +std::string +get_node_value(const pugi::xml_node &node, const char *name) +{ + // Search for either an attribute or child tag and get the data as a char*. + const pugi::char_t *value_char; + if (node.attribute(name)) { + value_char = node.attribute(name).value(); + } else if (node.child(name)) { + value_char = node.child_value(name); + } else { + std::string err_msg("Node \""); + err_msg += name; + err_msg += "\" is not a memeber of the \""; + err_msg += node.name(); + err_msg += "\" XML node"; + fatal_error(err_msg); + } + + // Convert to lowercase string. + std::string value(value_char); + std::transform(value.begin(), value.end(), value.begin(), ::tolower); + + // Remove whitespace. + value.erase(0, value.find_first_not_of(" \t\r\n")); + value.erase(value.find_last_not_of(" \t\r\n") + 1); + + return value; +} + +#endif // XML_INTERFACE_H From 75501a08e931ed64011205bbd612e708eb0bb670 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Wed, 24 Jan 2018 11:56:20 -0500 Subject: [PATCH 030/212] Add C++ Surface pointers to Fortran Surfaces --- src/geometry.F90 | 68 +--------- src/input_xml.F90 | 60 +-------- src/output.F90 | 2 +- src/summary.F90 | 15 +-- src/surface.cpp | 13 +- src/surface.h | 72 +++++------ src/surface_header.F90 | 180 ++++++++++++++++++++++++++- src/tallies/tally_filter_surface.F90 | 2 +- src/tracking.F90 | 43 ++++--- 9 files changed, 252 insertions(+), 203 deletions(-) diff --git a/src/geometry.F90 b/src/geometry.F90 index d1519f8d21..0bacd7b5d1 100644 --- a/src/geometry.F90 +++ b/src/geometry.F90 @@ -14,66 +14,6 @@ module geometry implicit none - interface - pure function surface_sense_c(surf_ind, xyz, uvw) & - bind(C, name='surface_sense') result(sense) - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind; - real(C_DOUBLE), intent(in) :: xyz(3); - real(C_DOUBLE), intent(in) :: uvw(3); - logical(C_BOOL) :: sense; - end function surface_sense_c - - pure subroutine surface_reflect_c(surf_ind, xyz, uvw) & - bind(C, name='surface_reflect') - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind; - real(C_DOUBLE), intent(in) :: xyz(3); - real(C_DOUBLE), intent(inout) :: uvw(3); - end subroutine surface_reflect_c - - pure function surface_distance_c(surf_ind, xyz, uvw, coincident) & - bind(C, name='surface_distance') result(d) - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind; - real(C_DOUBLE), intent(in) :: xyz(3); - real(C_DOUBLE), intent(in) :: uvw(3); - logical(C_BOOL), intent(in), value :: coincident; - real(C_DOUBLE) :: d; - end function surface_distance_c - - pure subroutine surface_normal_c(surf_ind, xyz, uvw) & - bind(C, name='surface_normal') - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind; - real(C_DOUBLE), intent(in) :: xyz(3); - real(C_DOUBLE), intent(out) :: uvw(3); - end subroutine surface_normal_c - - function surface_periodic_c(surf_ind1, xyz, uvw) & - bind(C, name="surface_periodic") result(rotational) - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind1; - real(C_DOUBLE), intent(inout) :: xyz(3); - real(C_DOUBLE), intent(inout) :: uvw(3); - logical(C_BOOL) :: rotational - end function surface_periodic_c - - function surface_i_periodic_c(surf_ind) bind(C, name="surface_i_periodic") & - result(i_periodic) - use ISO_C_BINDING - implicit none - integer(C_INT), intent(in), value :: surf_ind - integer(C_INT) :: i_periodic - end function - - end interface - contains !=============================================================================== @@ -125,7 +65,7 @@ contains in_cell = .false. exit else - actual_sense = surface_sense_c(abs(token)-1, & + actual_sense = surfaces(abs(token)) % sense( & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) if (actual_sense .neqv. (token > 0)) then in_cell = .false. @@ -174,7 +114,7 @@ contains elseif (-token == p%surface) then stack(i_stack) = .false. else - actual_sense = surface_sense_c(abs(token)-1, & + actual_sense = surfaces(abs(token)) % sense( & p%coord(p%n_coord)%xyz, p%coord(p%n_coord)%uvw) stack(i_stack) = (actual_sense .eqv. (token > 0)) end if @@ -579,7 +519,7 @@ contains if (index_surf >= OP_UNION) cycle ! Calculate distance to surface - d = surface_distance_c(index_surf-1, p % coord(j) % xyz, & + d = surfaces(index_surf) % distance(p % coord(j) % xyz, & p % coord(j) % uvw, logical(coincident, kind=C_BOOL)) ! Check if calculated distance is new minimum @@ -799,7 +739,7 @@ contains ! traveling into if the surface is crossed if (.not. c % simple) then xyz_cross(:) = p % coord(j) % xyz + d_surf*p % coord(j) % uvw - call surface_normal_c(abs(level_surf_cross)-1, xyz_cross, surf_uvw) + call surfaces(abs(level_surf_cross)) % normal(xyz_cross, surf_uvw) if (dot_product(p % coord(j) % uvw, surf_uvw) > ZERO) then surface_crossed = abs(level_surf_cross) else diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 9b6e1c6fce..55eeca9e14 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -924,19 +924,15 @@ contains logical :: file_exists logical :: boundary_exists character(MAX_LINE_LEN) :: filename - character(MAX_WORD_LEN) :: word character(MAX_WORD_LEN), allocatable :: sarray(:) character(:), allocatable :: region_spec type(Cell), pointer :: c - class(Surface), pointer :: s class(Lattice), pointer :: lat type(XMLDocument) :: doc type(XMLNode) :: root type(XMLNode) :: node_cell - type(XMLNode) :: node_surf type(XMLNode) :: node_lat type(XMLNode), allocatable :: node_cell_list(:) - type(XMLNode), allocatable :: node_surf_list(:) type(XMLNode), allocatable :: node_rlat_list(:) type(XMLNode), allocatable :: node_hlat_list(:) type(VectorInt) :: tokens @@ -968,66 +964,18 @@ contains ! applied to a surface boundary_exists = .false. - ! get pointer to list of xml - call get_node_list(root, "surface", node_surf_list) call read_surfaces(root % ptr) - ! Get number of tags - n_surfaces = size(node_surf_list) - - ! Check for no surfaces - if (n_surfaces == 0) then - call fatal_error("No surfaces found in geometry.xml!") - end if - - ! Allocate cells array + ! Allocate surfaces array allocate(surfaces(n_surfaces)) do i = 1, n_surfaces - ! Get pointer to i-th surface node - node_surf = node_surf_list(i) + surfaces(i) % ptr = surface_pointer_c(i - 1); - s => surfaces(i) + if (surfaces(i) % bc() /= BC_TRANSMIT) boundary_exists = .true. - ! Copy data into cells - if (check_for_node(node_surf, "id")) then - call get_node_value(node_surf, "id", s%id) - else - call fatal_error("Must specify id of surface in geometry XML file.") - end if - - ! Check to make sure 'id' hasn't been used - if (surface_dict % has(s%id)) then - call fatal_error("Two or more surfaces use the same unique ID: " & - // to_str(s%id)) - end if - - ! Check to make sure that the proper number of coefficients - ! have been specified for the given type of surface. Then copy - ! surface coordinates. - - ! Boundary conditions - word = '' - if (check_for_node(node_surf, "boundary")) & - call get_node_value(node_surf, "boundary", word) - select case (to_lower(word)) - case ('transmission', 'transmit', '') - s%bc = BC_TRANSMIT - case ('vacuum') - s%bc = BC_VACUUM - boundary_exists = .true. - case ('reflective', 'reflect', 'reflecting') - s%bc = BC_REFLECT - boundary_exists = .true. - case ('periodic') - s%bc = BC_PERIODIC - boundary_exists = .true. - case default - call fatal_error("Unknown boundary condition '" // trim(word) // & - &"' specified on surface " // trim(to_str(s%id))) - end select ! Add surface to dictionary - call surface_dict % set(s%id, i) + call surface_dict % set(surfaces(i) % id(), i) end do ! Check to make sure a boundary condition was applied to at least one diff --git a/src/output.F90 b/src/output.F90 index 4113eea472..316fe95941 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -259,7 +259,7 @@ contains ! Print surface if (p % surface /= NONE) then - write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%id, p % surface)) + write(ou,*) ' Surface = ' // to_str(sign(surfaces(i)%id(), p % surface)) end if ! Display weight, energy, grid index, and interpolation factor diff --git a/src/summary.F90 b/src/summary.F90 index 9b82a03967..3aeb42178b 100644 --- a/src/summary.F90 +++ b/src/summary.F90 @@ -24,17 +24,6 @@ module summary public :: write_summary - interface - subroutine surface_to_hdf5_c(surf_ind, group) & - bind(C, name='surface_to_hdf5') - use ISO_C_BINDING - use hdf5 - implicit none - integer(C_INT), intent(in), value :: surf_ind - integer(HID_T), intent(in), value :: group - end subroutine surface_to_hdf5_c - end interface - contains !=============================================================================== @@ -232,7 +221,7 @@ contains region_spec = trim(region_spec) // " |" case default region_spec = trim(region_spec) // " " // to_str(& - sign(surfaces(abs(k))%id, k)) + sign(surfaces(abs(k))%id(), k)) end select end do call write_dataset(cell_group, "region", adjustl(region_spec)) @@ -250,7 +239,7 @@ contains ! Write information on each surface SURFACE_LOOP: do i = 1, n_surfaces - call surface_to_hdf5_c(i-1, surfaces_group) + call surfaces(i) % to_hdf5(surfaces_group) end do SURFACE_LOOP call close_group(surfaces_group) diff --git a/src/surface.cpp b/src/surface.cpp index ed111b0370..369334d500 100644 --- a/src/surface.cpp +++ b/src/surface.cpp @@ -1053,11 +1053,13 @@ extern "C" void read_surfaces(pugi::xml_node *node) { // Count the number of surfaces. - int n_surfaces{0}; for (pugi::xml_node surf_node = node->child("surface"); surf_node; surf_node = surf_node.next_sibling("surface")) { n_surfaces++; } + if (n_surfaces == 0) { + fatal_error("No surfaces found in geometry.xml!"); + } // Allocate the array of Surface pointers. surfaces_c = new Surface* [n_surfaces]; @@ -1137,7 +1139,14 @@ read_surfaces(pugi::xml_node *node) // Downcast to the PeriodicSurface type. Surface *surf_base = surfaces_c[i_surf]; PeriodicSurface *surf = dynamic_cast(surf_base); - //TODO: check for null pointer + + // Make sure this surface inherits from PeriodicSurface. + if (surf == NULL) { + std::string err_msg{"Periodic boundary condition not supported for " + "surface "}; + err_msg += std::to_string(surf_base->id); + err_msg += ". Periodic BCs are only supported for planar surfaces."; + } // See if this surface makes part of the global bounding box. struct BoundingBox bb = surf->bounding_box(); diff --git a/src/surface.h b/src/surface.h index 22eb798dcb..469d884862 100644 --- a/src/surface.h +++ b/src/surface.h @@ -28,6 +28,8 @@ const int C_NONE{-1}; // Global variables //============================================================================== +int n_surfaces{0}; + class Surface; Surface **surfaces_c; @@ -375,57 +377,43 @@ public: // Fortran compatibility functions //============================================================================== -extern "C" bool -surface_sense(int surf_ind, double xyz[3], double uvw[3]) -{ - return surfaces_c[surf_ind]->sense(xyz, uvw); -} +extern "C" Surface* surface_pointer(int surf_ind) {return surfaces_c[surf_ind];} -extern "C" void -surface_reflect(int surf_ind, double xyz[3], double uvw[3]) -{ - surfaces_c[surf_ind]->reflect(xyz, uvw); -} +extern "C" int surface_id(Surface *surf) {return surf->id;} + +extern "C" int surface_bc(Surface *surf) {return surf->bc;} + +extern "C" bool surface_sense(Surface *surf, double xyz[3], double uvw[3]) +{return surf->sense(xyz, uvw);} + +extern "C" void surface_reflect(Surface *surf, double xyz[3], double uvw[3]) +{surf->reflect(xyz, uvw);} extern "C" double -surface_distance(int surf_ind, double xyz[3], double uvw[3], bool coincident) -{ - return surfaces_c[surf_ind]->distance(xyz, uvw, coincident); -} +surface_distance(Surface *surf, double xyz[3], double uvw[3], bool coincident) +{return surf->distance(xyz, uvw, coincident);} -extern "C" void -surface_normal(int surf_ind, double xyz[3], double uvw[3]) -{ - return surfaces_c[surf_ind]->normal(xyz, uvw); -} +extern "C" void surface_normal(Surface *surf, double xyz[3], double uvw[3]) +{return surf->normal(xyz, uvw);} -extern "C" void -surface_to_hdf5(int surf_ind, hid_t group) -{ - surfaces_c[surf_ind]->to_hdf5(group); -} +extern "C" void surface_to_hdf5(Surface *surf, hid_t group) +{surf->to_hdf5(group);} + +extern "C" int surface_i_periodic(PeriodicSurface *surf) +{return surf->i_periodic;} extern "C" bool -surface_periodic(int surf_ind1, double xyz[3], double uvw[3]) -{ - // Hopefully this function has only been called for a pair of surfaces that - // support periodic BCs (checking should have been done when reading the - // geometry XML). Downcast the surfaces to the PeriodicSurface type so we - // can call the periodic_translate method. - Surface *surf1_gen = surfaces_c[surf_ind1]; - PeriodicSurface *surf1 = dynamic_cast(surf1_gen); - Surface *surf2_gen = surfaces_c[surf1->i_periodic]; - PeriodicSurface *surf2 = dynamic_cast(surf2_gen); +surface_periodic(PeriodicSurface *surf, PeriodicSurface *other, double xyz[3], + double uvw[3]) +{return surf->periodic_translate(other, xyz, uvw);} - // Call the type-bound methods. - return surf2->periodic_translate(surf1, xyz, uvw); -} - -extern "C" int -surface_i_periodic(int surf_ind) +extern "C" void free_memory_surfaces_c() { - PeriodicSurface *surf = dynamic_cast(surfaces_c[surf_ind]); - return surf->i_periodic; + for (int i = 0; i < n_surfaces; i++) {delete surfaces_c[i];} + delete surfaces_c; + surfaces_c = NULL; + n_surfaces = 0; + surface_dict.clear(); } #endif // SURFACE_H diff --git a/src/surface_header.F90 b/src/surface_header.F90 index ffe0a6db41..8985e8406e 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -1,26 +1,132 @@ module surface_header use, intrinsic :: ISO_C_BINDING + use hdf5 - use constants, only: NONE use dict_header, only: DictIntInt implicit none + interface + pure function surface_pointer_c(surf_ind) & + bind(C, name='surface_pointer') result(ptr) + use ISO_C_BINDING + implicit none + integer(C_INT), intent(in), value :: surf_ind + type(C_PTR) :: ptr + end function surface_pointer_c + + pure function surface_id_c(surf_ptr) bind(C, name='surface_id') result(id) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: id + end function surface_id_c + + pure function surface_bc_c(surf_ptr) bind(C, name='surface_bc') result(bc) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: bc + end function surface_bc_c + + pure function surface_sense_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_sense') result(sense) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3) + real(C_DOUBLE), intent(in) :: uvw(3) + logical(C_BOOL) :: sense + end function surface_sense_c + + pure subroutine surface_reflect_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_reflect') + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + end subroutine surface_reflect_c + + pure function surface_distance_c(surf_ptr, xyz, uvw, coincident) & + bind(C, name='surface_distance') result(d) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL), intent(in), value :: coincident; + real(C_DOUBLE) :: d; + end function surface_distance_c + + pure subroutine surface_normal_c(surf_ptr, xyz, uvw) & + bind(C, name='surface_normal') + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(out) :: uvw(3); + end subroutine surface_normal_c + + subroutine surface_to_hdf5_c(surf_ptr, group) & + bind(C, name='surface_to_hdf5') + use ISO_C_BINDING + use hdf5 + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(HID_T), intent(in), value :: group + end subroutine surface_to_hdf5_c + + pure function surface_i_periodic_c(surf_ptr) & + bind(C, name="surface_i_periodic") result(i_periodic) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + integer(C_INT) :: i_periodic + end function surface_i_periodic_c + + function surface_periodic_c(surf_ptr, other_ptr, xyz, uvw) & + bind(C, name="surface_periodic") result(rotational) + use ISO_C_BINDING + implicit none + type(C_PTR), intent(in), value :: surf_ptr + type(C_PTR), intent(in), value :: other_ptr + real(C_DOUBLE), intent(inout) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + logical(C_BOOL) :: rotational + end function surface_periodic_c + + subroutine free_memory_surfaces_c() bind(C) + end subroutine free_memory_surfaces_c + end interface + !=============================================================================== ! SURFACE type defines a first- or second-order surface that can be used to ! construct closed volumes (cells) !=============================================================================== type :: Surface - integer :: id ! Unique ID integer, allocatable :: & neighbor_pos(:), & ! List of cells on positive side neighbor_neg(:) ! List of cells on negative side - integer :: bc ! Boundary condition + type(C_PTR) :: ptr + + contains + + procedure :: id => surface_id + procedure :: bc => surface_bc + procedure :: sense => surface_sense + procedure :: reflect => surface_reflect + procedure :: distance => surface_distance + procedure :: normal => surface_normal + procedure :: to_hdf5 => surface_to_hdf5 + procedure :: i_periodic => surface_i_periodic + procedure :: periodic_translate => surface_periodic + end type Surface - integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces + integer(C_INT), bind(C) :: n_surfaces ! # of surfaces type(Surface), allocatable, target :: surfaces(:) @@ -29,14 +135,78 @@ module surface_header contains + pure function surface_id(this) result(id) + class(Surface), intent(in) :: this + integer(C_INT) :: id + id = surface_id_c(this % ptr) + end function surface_id + + pure function surface_bc(this) result(bc) + class(Surface), intent(in) :: this + integer(C_INT) :: bc + bc = surface_bc_c(this % ptr) + end function surface_bc + + pure function surface_sense(this, xyz, uvw) result(sense) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3) + real(C_DOUBLE), intent(in) :: uvw(3) + logical(C_BOOL) :: sense + sense = surface_sense_c(this % ptr, xyz, uvw) + end function surface_sense + + pure subroutine surface_reflect(this, xyz, uvw) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + call surface_reflect_c(this % ptr, xyz, uvw) + end subroutine surface_reflect + + pure function surface_distance(this, xyz, uvw, coincident) result(d) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(in) :: uvw(3); + logical(C_BOOL), intent(in) :: coincident; + real(C_DOUBLE) :: d; + d = surface_distance_c(this % ptr, xyz, uvw, coincident) + end function surface_distance + + pure subroutine surface_normal(this, xyz, uvw) + class(Surface), intent(in) :: this + real(C_DOUBLE), intent(in) :: xyz(3); + real(C_DOUBLE), intent(out) :: uvw(3); + call surface_normal_c(this % ptr, xyz, uvw) + end subroutine surface_normal + + subroutine surface_to_hdf5(this, group) + class(Surface), intent(in) :: this + integer(HID_T), intent(in) :: group + call surface_to_hdf5_c(this % ptr, group) + end subroutine surface_to_hdf5 + + pure function surface_i_periodic(this) result(i_periodic) + class(Surface), intent(in) :: this + integer(C_INT) :: i_periodic + i_periodic = surface_i_periodic_c(this % ptr) + end function surface_i_periodic + + function surface_periodic(this, other, xyz, uvw) result(rotational) + class(Surface), intent(in) :: this + class(Surface), intent(in) :: other + real(C_DOUBLE), intent(inout) :: xyz(3); + real(C_DOUBLE), intent(inout) :: uvw(3); + logical(C_BOOL) :: rotational + rotational = surface_periodic_c(this % ptr, other % ptr, xyz, uvw) + end function surface_periodic + !=============================================================================== ! FREE_MEMORY_SURFACES deallocates global arrays defined in this module !=============================================================================== subroutine free_memory_surfaces() - n_surfaces = 0 if (allocated(surfaces)) deallocate(surfaces) call surface_dict % clear() + call free_memory_surfaces_c() end subroutine free_memory_surfaces end module surface_header diff --git a/src/tallies/tally_filter_surface.F90 b/src/tallies/tally_filter_surface.F90 index 6a2afa3ec6..df3bf36031 100644 --- a/src/tallies/tally_filter_surface.F90 +++ b/src/tallies/tally_filter_surface.F90 @@ -105,7 +105,7 @@ contains integer, intent(in) :: bin character(MAX_LINE_LEN) :: label - label = "Surface " // to_str(surfaces(this % surfaces(bin)) % id) + label = "Surface " // to_str(surfaces(this % surfaces(bin)) % id()) end function text_label_surface end module tally_filter_surface diff --git a/src/tracking.F90 b/src/tracking.F90 index 98bca2a279..75555c7974 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -4,9 +4,8 @@ module tracking use cross_section, only: calculate_xs use error, only: fatal_error, warning, write_message use geometry_header, only: cells - use geometry, only: find_cell, distance_to_boundary, cross_lattice, & - check_cell_overlap, surface_reflect_c, & - surface_periodic_c, surface_i_periodic_c + use geometry, only: find_cell, distance_to_boundary, cross_lattice,& + check_cell_overlap use message_passing use mgxs_header use nuclide_header @@ -296,14 +295,15 @@ contains logical :: rotational ! if rotational periodic BC applied logical :: found ! particle found in universe? class(Surface), pointer :: surf + class(Surface), pointer :: surf2 ! periodic partner surface i_surface = abs(p % surface) surf => surfaces(i_surface) if (verbosity >= 10 .or. trace) then - call write_message(" Crossing surface " // trim(to_str(surf % id))) + call write_message(" Crossing surface " // trim(to_str(surf % id()))) end if - if (surf % bc == BC_VACUUM .and. (run_mode /= MODE_PLOTTING)) then + if (surf % bc() == BC_VACUUM .and. (run_mode /= MODE_PLOTTING)) then ! ======================================================================= ! PARTICLE LEAKS OUT OF PROBLEM @@ -328,11 +328,11 @@ contains ! Display message if (verbosity >= 10 .or. trace) then call write_message(" Leaked out of surface " & - &// trim(to_str(surf % id))) + &// trim(to_str(surf % id()))) end if return - elseif (surf % bc == BC_REFLECT .and. (run_mode /= MODE_PLOTTING)) then + elseif (surf % bc() == BC_REFLECT .and. (run_mode /= MODE_PLOTTING)) then ! ======================================================================= ! PARTICLE REFLECTS FROM SURFACE @@ -355,7 +355,7 @@ contains end if ! Reflect particle off surface - call surface_reflect_c(i_surface-1, p%coord(1)%xyz, p%coord(1)%uvw) + call surf % reflect(p%coord(1)%xyz, p%coord(1)%uvw) ! Make sure new particle direction is normalized u = p%coord(1)%uvw(1) @@ -376,7 +376,7 @@ contains call find_cell(p, found) if (.not. found) then call p % mark_as_lost("Couldn't find particle after reflecting& - & from surface " // trim(to_str(surf % id)) // ".") + & from surface " // trim(to_str(surf % id())) // ".") return end if @@ -386,10 +386,10 @@ contains ! Diagnostic message if (verbosity >= 10 .or. trace) then call write_message(" Reflected from surface " & - &// trim(to_str(surf%id))) + &// trim(to_str(surf%id()))) end if return - elseif (surf % bc == BC_PERIODIC .and. run_mode /= MODE_PLOTTING) then + elseif (surf % bc() == BC_PERIODIC .and. run_mode /= MODE_PLOTTING) then ! ======================================================================= ! PERIODIC BOUNDARY @@ -404,7 +404,6 @@ contains ! Score surface currents since reflection causes the direction of the ! particle to change -- artificially move the particle slightly back in ! case the surface crossing is coincident with a mesh boundary - if (active_current_tallies % size() > 0) then xyz = p % coord(1) % xyz p % coord(1) % xyz = p % coord(1) % xyz - TINY_BIT * p % coord(1) % uvw @@ -412,14 +411,19 @@ contains p % coord(1) % xyz = xyz end if - rotational = surface_periodic_c(i_surface-1, p % coord(1) % xyz, & - p % coord(1) % uvw) + ! Get a pointer to the partner periodic surface. Offset the index to + ! correct for C vs. Fortran indexing. + surf2 => surfaces(surf % i_periodic() + 1) + + ! Adjust the particle's location and direction. + rotational = surf2 % periodic_translate(surf, p % coord(1) % xyz, & + p % coord(1) % uvw) ! Reassign particle's surface if (rotational) then - p % surface = surface_i_periodic_c(i_surface-1) + 1 + p % surface = surf % i_periodic() + 1 else - p % surface = sign(surface_i_periodic_c(i_surface-1) + 1, p % surface) + p % surface = sign(surf % i_periodic() + 1, p % surface) end if ! Figure out what cell particle is in now @@ -427,7 +431,8 @@ contains call find_cell(p, found) if (.not. found) then call p % mark_as_lost("Couldn't find particle after hitting & - &periodic boundary on surface " // trim(to_str(surf % id)) // ".") + &periodic boundary on surface " // trim(to_str(surf % id())) & + // ".") return end if @@ -437,7 +442,7 @@ contains ! Diagnostic message if (verbosity >= 10 .or. trace) then call write_message(" Hit periodic boundary on surface " & - // trim(to_str(surf%id))) + // trim(to_str(surf%id()))) end if return end if @@ -484,7 +489,7 @@ contains if (.not. found) then call p % mark_as_lost("After particle " // trim(to_str(p % id)) & - // " crossed surface " // trim(to_str(surf % id)) & + // " crossed surface " // trim(to_str(surf % id())) & // " it could not be located in any cell and it did not leak.") return end if From ced4c05400d3c3b96f8037366163748cd7ab406d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 26 Jan 2018 13:24:10 -0600 Subject: [PATCH 031/212] Use contiguous derived MPI type to avoid broadcasting counts > 2**31 - 1 --- CMakeLists.txt | 5 ++++- src/simulation.F90 | 21 ++++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 51bdcc4d9f..8104b5fb1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,6 +50,9 @@ if($ENV{FC} MATCHES "(mpi[^/]*|ftn)$") message("-- Detected MPI wrapper: $ENV{FC}") add_definitions(-DMPI) set(MPI_ENABLED TRUE) + + # Get directory containing MPI wrapper + get_filename_component(MPI_DIR $ENV{FC} DIRECTORY) endif() # Check for Fortran 2008 MPI interface @@ -552,7 +555,7 @@ foreach(test ${TESTS}) add_test(NAME ${TEST_NAME} WORKING_DIRECTORY ${TEST_PATH} COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $ - --mpi_exec $ENV{MPI_DIR}/bin/mpiexec) + --mpi_exec ${MPI_DIR}/mpiexec) else() # Perform a serial test add_test(NAME ${TEST_NAME} diff --git a/src/simulation.F90 b/src/simulation.F90 index ef29e7832b..061ca2fdae 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -472,8 +472,14 @@ contains #ifdef MPI integer :: n ! size of arrays integer :: mpi_err ! MPI error code + integer :: count_per_filter ! number of result values for one filter bin integer(8) :: temp real(8) :: tempr(3) ! temporary array for communication +#ifdef MPIF08 + type(MPI_Datatype) :: result_block +#else + integer :: result_block +#endif #endif ! Skip if simulation was never run @@ -498,9 +504,18 @@ contains ! Broadcast tally results so that each process has access to results if (allocated(tallies)) then do i = 1, size(tallies) - n = size(tallies(i) % obj % results) - call MPI_BCAST(tallies(i) % obj % results, n, MPI_DOUBLE, 0, & - mpi_intracomm, mpi_err) + associate (results => tallies(i) % obj % results) + ! Create a new datatype that consists of all values for a given filter + ! bin and then use that to broadcast. This is done to minimize the + ! chance of the 'count' argument of MPI_BCAST exceeding 2**31 + n = size(results, 3) + count_per_filter = size(results, 1) * size(results, 2) + call MPI_TYPE_CONTIGUOUS(count_per_filter, MPI_DOUBLE, & + result_block, mpi_err) + call MPI_TYPE_COMMIT(result_block, mpi_err) + call MPI_BCAST(results, n, result_block, 0, mpi_intracomm, mpi_err) + call MPI_TYPE_FREE(result_block, mpi_err) + end associate end do end if From 52905d4364bfead5d1c11fb1acbcd7128d08b95d Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Wed, 31 Jan 2018 15:28:36 -0500 Subject: [PATCH 032/212] Address #959 comments --- src/error.F90 | 6 +- src/error.h | 12 +++ src/hdf5_interface.h | 4 + src/random_lcg.cpp | 5 ++ src/random_lcg.h | 4 + src/surface.cpp | 188 ++++++++++++++++++++--------------------- src/surface.h | 24 ++++-- src/surface_header.F90 | 2 +- src/xml_interface.h | 24 +++--- 9 files changed, 147 insertions(+), 122 deletions(-) diff --git a/src/error.F90 b/src/error.F90 index cba1372917..0a5af302d6 100644 --- a/src/error.F90 +++ b/src/error.F90 @@ -195,9 +195,9 @@ contains end subroutine fatal_error subroutine fatal_error_from_c(message, message_len) bind(C) - integer(C_INT), intent(in), value :: message_len - character(C_CHAR), intent(in) :: message(message_len) - character(message_len+1) :: message_out + integer(C_INT), intent(in), value :: message_len + character(kind=C_CHAR), intent(in) :: message(message_len) + character(message_len+1) :: message_out write(message_out, *) message call fatal_error(message_out) end subroutine diff --git a/src/error.h b/src/error.h index 0fd78a6c5c..4c3373b3e3 100644 --- a/src/error.h +++ b/src/error.h @@ -3,6 +3,10 @@ #include #include +#include + + +namespace openmc { extern "C" void fatal_error_from_c(const char *message, int message_len); @@ -19,4 +23,12 @@ void fatal_error(const std::string &message) fatal_error_from_c(message.c_str(), message.length()); } + +void fatal_error(const std::stringstream &message) +{ + std::string out {message.str()}; + fatal_error_from_c(out.c_str(), out.length()); +} + +} // namespace openmc #endif // ERROR_H diff --git a/src/hdf5_interface.h b/src/hdf5_interface.h index 2cded21f64..7ec9ada9b6 100644 --- a/src/hdf5_interface.h +++ b/src/hdf5_interface.h @@ -9,6 +9,9 @@ #include "error.h" +namespace openmc { + + hid_t create_group(hid_t parent_id, char const *name) { @@ -84,4 +87,5 @@ write_string(hid_t group_id, char const *name, const std::string &buffer) write_string(group_id, name, buffer.c_str()); } +} // namespace openmc #endif //HDF5_INTERFACE_H diff --git a/src/random_lcg.cpp b/src/random_lcg.cpp index 047bda8e54..2dcdd86a36 100644 --- a/src/random_lcg.cpp +++ b/src/random_lcg.cpp @@ -2,6 +2,9 @@ #include +namespace openmc { + + // Constants extern "C" const int N_STREAMS {5}; extern "C" const int STREAM_TRACKING {0}; @@ -143,3 +146,5 @@ openmc_set_seed(int64_t new_seed) } return 0; } + +} // namespace openmc diff --git a/src/random_lcg.h b/src/random_lcg.h index 04191254f3..cd065474ea 100644 --- a/src/random_lcg.h +++ b/src/random_lcg.h @@ -3,6 +3,9 @@ #include + +namespace openmc { + //============================================================================== // Module constants. //============================================================================== @@ -82,4 +85,5 @@ extern "C" void prn_set_stream(int n); extern "C" int openmc_set_seed(int64_t new_seed); +} // namespace openmc #endif // RANDOM_LCG_H diff --git a/src/surface.cpp b/src/surface.cpp index 369334d500..16f333f7e1 100644 --- a/src/surface.cpp +++ b/src/surface.cpp @@ -1,11 +1,15 @@ +#include "surface.h" + #include -#include // For fabs +#include #include "error.h" #include "hdf5_interface.h" #include "xml_interface.h" +#include -#include "surface.h" + +namespace openmc { //============================================================================== // Helper functions for reading the "coeffs" node of an XML surface element @@ -14,7 +18,7 @@ int word_count(const std::string &text) { bool in_word = false; - int count{0}; + int count {0}; for (auto c = text.begin(); c != text.end(); c++) { if (std::isspace(*c)) { if (in_word) { @@ -35,10 +39,9 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1) std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 1) { - std::string err_msg{"Surface "}; - err_msg += std::to_string(surf_id); - err_msg += " expects 1 coeff but was given "; - err_msg += std::to_string(n_words); + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 1 coeff but was given " + << n_words; fatal_error(err_msg); } @@ -56,10 +59,9 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 3) { - std::string err_msg{"Surface "}; - err_msg += std::to_string(surf_id); - err_msg += " expects 3 coeffs but was given "; - err_msg += std::to_string(n_words); + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 3 coeffs but was given " + << n_words; fatal_error(err_msg); } @@ -77,10 +79,9 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 4) { - std::string err_msg{"Surface "}; - err_msg += std::to_string(surf_id); - err_msg += " expects 4 coeffs but was given "; - err_msg += std::to_string(n_words); + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 4 coeffs but was given " + << n_words; fatal_error(err_msg); } @@ -99,10 +100,9 @@ void read_coeffs(pugi::xml_node surf_node, int surf_id, double &c1, double &c2, std::string coeffs = get_node_value(surf_node, "coeffs"); int n_words = word_count(coeffs); if (n_words != 10) { - std::string err_msg{"Surface "}; - err_msg += std::to_string(surf_id); - err_msg += " expects 10 coeffs but was given "; - err_msg += std::to_string(n_words); + std::stringstream err_msg; + err_msg << "Surface " << surf_id << " expects 10 coeffs but was given " + << n_words; fatal_error(err_msg); } @@ -133,23 +133,21 @@ Surface::Surface(pugi::xml_node surf_node) if (check_for_node(surf_node, "boundary")) { std::string surf_bc = get_node_value(surf_node, "boundary"); - if (surf_bc.compare("transmission") == 0 - or surf_bc.compare("transmit") == 0 - or surf_bc.compare("") == 0) { + if (surf_bc == "transmission" || surf_bc == "transmit" ||surf_bc.empty()) { bc = BC_TRANSMIT; - } else if (surf_bc.compare("vacuum") == 0) { + } else if (surf_bc == "vacuum") { bc = BC_VACUUM; - } else if (surf_bc.compare("reflective") == 0 - or surf_bc.compare("reflect") == 0 - or surf_bc.compare("reflecting") == 0) { + } else if (surf_bc == "reflective" || surf_bc == "reflect" + || surf_bc == "reflecting") { bc = BC_REFLECT; - } else if (surf_bc.compare("periodic") == 0) { + } else if (surf_bc == "periodic") { bc = BC_PERIODIC; } else { - std::string err_msg("Unknown boundary condition \""); - err_msg += surf_bc + "\" specified on surface " + std::to_string(id); + std::stringstream err_msg; + err_msg << "Unknown boundary condition \"" << surf_bc + << "\" specified on surface " << id; fatal_error(err_msg); } @@ -167,7 +165,7 @@ Surface::sense(const double xyz[3], const double uvw[3]) const const double f = evaluate(xyz); // Check which side of surface the point is on. - if (fabs(f) < FP_COINCIDENT) { + if (std::abs(f) < FP_COINCIDENT) { // Particle may be coincident with this surface. To determine the sense, we // look at the direction of the particle relative to the surface normal (by // default in the positive direction) via their dot product. @@ -197,7 +195,7 @@ Surface::reflect(const double xyz[3], double uvw[3]) const void Surface::to_hdf5(hid_t group_id) const { - std::string group_name{"surface "}; + std::string group_name {"surface "}; group_name += std::to_string(id); hid_t surf_group = create_group(group_id, group_name); @@ -217,7 +215,7 @@ Surface::to_hdf5(hid_t group_id) const break; } - if (name.compare("")) { + if (!name.empty()) { write_string(surf_group, "name", name); } @@ -231,7 +229,7 @@ Surface::to_hdf5(hid_t group_id) const //============================================================================== PeriodicSurface::PeriodicSurface(pugi::xml_node surf_node) - : Surface(surf_node) + : Surface {surf_node} { if (check_for_node(surf_node, "periodic_surface_id")) { i_periodic = stoi(get_node_value(surf_node, "periodic_surface_id")); @@ -255,7 +253,7 @@ axis_aligned_plane_distance(const double xyz[3], const double uvw[3], bool coincident, double offset) { const double f = offset - xyz[i]; - if (coincident or fabs(f) < FP_COINCIDENT or uvw[i] == 0.0) return INFTY; + if (coincident or std::abs(f) < FP_COINCIDENT or uvw[i] == 0.0) return INFTY; const double d = f / uvw[i]; if (d < 0.0) return INFTY; return d; @@ -300,7 +298,7 @@ inline void SurfaceXPlane::normal(const double xyz[3], double uvw[3]) const void SurfaceXPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-plane"); - std::array coeffs{{x0}}; + std::array coeffs {{x0}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -320,7 +318,6 @@ bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], double y0 = -other->evaluate(xyz_test); xyz[1] = xyz[0] - x0 + y0; xyz[0] = x0; - xyz[2] = xyz[2]; double u = uvw[0]; uvw[0] = -uvw[1]; @@ -330,10 +327,10 @@ bool SurfaceXPlane::periodic_translate(PeriodicSurface *other, double xyz[3], } } -struct BoundingBox +BoundingBox SurfaceXPlane::bounding_box() const { - struct BoundingBox out{x0, x0, -INFTY, INFTY, -INFTY, INFTY}; + BoundingBox out {x0, x0, -INFTY, INFTY, -INFTY, INFTY}; return out; } @@ -366,7 +363,7 @@ inline void SurfaceYPlane::normal(const double xyz[3], double uvw[3]) const void SurfaceYPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-plane"); - std::array coeffs{{y0}}; + std::array coeffs {{y0}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -396,10 +393,10 @@ bool SurfaceYPlane::periodic_translate(PeriodicSurface *other, double xyz[3], } } -struct BoundingBox +BoundingBox SurfaceYPlane::bounding_box() const { - struct BoundingBox out{-INFTY, INFTY, y0, y0, -INFTY, INFTY}; + BoundingBox out {-INFTY, INFTY, y0, y0, -INFTY, INFTY}; return out; } @@ -432,7 +429,7 @@ inline void SurfaceZPlane::normal(const double xyz[3], double uvw[3]) const void SurfaceZPlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-plane"); - std::array coeffs{{z0}}; + std::array coeffs {{z0}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -444,10 +441,10 @@ bool SurfaceZPlane::periodic_translate(PeriodicSurface *other, double xyz[3], return false; } -struct BoundingBox +BoundingBox SurfaceZPlane::bounding_box() const { - struct BoundingBox out{-INFTY, INFTY, -INFTY, INFTY, z0, z0}; + BoundingBox out {-INFTY, INFTY, -INFTY, INFTY, z0, z0}; return out; } @@ -473,7 +470,7 @@ SurfacePlane::distance(const double xyz[3], const double uvw[3], { const double f = A*xyz[0] + B*xyz[1] + C*xyz[2] - D; const double projection = A*uvw[0] + B*uvw[1] + C*uvw[2]; - if (coincident or fabs(f) < FP_COINCIDENT or projection == 0.0) { + if (coincident or std::abs(f) < FP_COINCIDENT or projection == 0.0) { return INFTY; } else { const double d = -f / projection; @@ -493,7 +490,7 @@ SurfacePlane::normal(const double xyz[3], double uvw[3]) const void SurfacePlane::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "plane"); - std::array coeffs{{A, B, C, D}}; + std::array coeffs {{A, B, C, D}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -513,10 +510,10 @@ bool SurfacePlane::periodic_translate(PeriodicSurface *other, double xyz[3], return false; } -struct BoundingBox +BoundingBox SurfacePlane::bounding_box() const { - struct BoundingBox out{-INFTY, INFTY, -INFTY, INFTY, -INFTY, INFTY}; + BoundingBox out {-INFTY, INFTY, -INFTY, INFTY, -INFTY, INFTY}; return out; } @@ -556,7 +553,7 @@ axis_aligned_cylinder_distance(const double xyz[3], const double uvw[3], // No intersection with cylinder. return INFTY; - } else if (coincident or fabs(c) < FP_COINCIDENT) { + } else if (coincident or std::abs(c) < FP_COINCIDENT) { // Particle is on the cylinder, thus one distance is positive/negative // and the other is zero. The sign of k determines if we are facing in or // out. @@ -625,7 +622,7 @@ inline void SurfaceXCylinder::normal(const double xyz[3], double uvw[3]) const void SurfaceXCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-cylinder"); - std::array coeffs{{y0, z0, r}}; + std::array coeffs {{y0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -659,7 +656,7 @@ inline void SurfaceYCylinder::normal(const double xyz[3], double uvw[3]) const void SurfaceYCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-cylinder"); - std::array coeffs{{x0, z0, r}}; + std::array coeffs {{x0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -693,7 +690,7 @@ inline void SurfaceZCylinder::normal(const double xyz[3], double uvw[3]) const void SurfaceZCylinder::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-cylinder"); - std::array coeffs{{x0, y0, r}}; + std::array coeffs {{x0, y0, r}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -729,7 +726,7 @@ double SurfaceSphere::distance(const double xyz[3], const double uvw[3], // No intersection with sphere. return INFTY; - } else if (coincident or fabs(c) < FP_COINCIDENT) { + } else if (coincident or std::abs(c) < FP_COINCIDENT) { // Particle is on the sphere, thus one distance is positive/negative and // the other is zero. The sign of k determines if we are facing in or out. if (k >= 0.0) { @@ -764,7 +761,7 @@ inline void SurfaceSphere::normal(const double xyz[3], double uvw[3]) const void SurfaceSphere::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "sphere"); - std::array coeffs{{x0, y0, z0, r}}; + std::array coeffs {{x0, y0, z0, r}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -808,7 +805,7 @@ axis_aligned_cone_distance(const double xyz[3], const double uvw[3], // No intersection with cone. return INFTY; - } else if (coincident or fabs(c) < FP_COINCIDENT) { + } else if (coincident or std::abs(c) < FP_COINCIDENT) { // Particle is on the cone, thus one distance is positive/negative // and the other is zero. The sign of k determines if we are facing in or // out. @@ -881,7 +878,7 @@ inline void SurfaceXCone::normal(const double xyz[3], double uvw[3]) const void SurfaceXCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "x-cone"); - std::array coeffs{{x0, y0, z0, r_sq}}; + std::array coeffs {{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -915,7 +912,7 @@ inline void SurfaceYCone::normal(const double xyz[3], double uvw[3]) const void SurfaceYCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "y-cone"); - std::array coeffs{{x0, y0, z0, r_sq}}; + std::array coeffs {{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -949,7 +946,7 @@ inline void SurfaceZCone::normal(const double xyz[3], double uvw[3]) const void SurfaceZCone::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "z-cone"); - std::array coeffs{{x0, y0, z0, r_sq}}; + std::array coeffs {{x0, y0, z0, r_sq}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -998,7 +995,7 @@ SurfaceQuadric::distance(const double xyz[3], // No intersection with surface. return INFTY; - } else if (coincident or fabs(c) < FP_COINCIDENT) { + } else if (coincident or std::abs(c) < FP_COINCIDENT) { // Particle is on the surface, thus one distance is positive/negative and // the other is zero. The sign of k determines which distance is zero and // which is not. @@ -1043,7 +1040,7 @@ SurfaceQuadric::normal(const double xyz[3], double uvw[3]) const void SurfaceQuadric::to_hdf5_inner(hid_t group_id) const { write_string(group_id, "type", "quadric"); - std::array coeffs{{A, B, C, D, E, F, G, H, J, K}}; + std::array coeffs {{A, B, C, D, E, F, G, H, J, K}}; write_double_1D(group_id, "coefficients", coeffs); } @@ -1053,10 +1050,7 @@ extern "C" void read_surfaces(pugi::xml_node *node) { // Count the number of surfaces. - for (pugi::xml_node surf_node = node->child("surface"); surf_node; - surf_node = surf_node.next_sibling("surface")) { - n_surfaces++; - } + for (pugi::xml_node surf_node: node->children("surface")) {n_surfaces++;} if (n_surfaces == 0) { fatal_error("No surfaces found in geometry.xml!"); } @@ -1072,46 +1066,45 @@ read_surfaces(pugi::xml_node *node) surf_node = surf_node.next_sibling("surface"), i_surf++) { std::string surf_type = get_node_value(surf_node, "type"); - if (surf_type.compare("x-plane") == 0) { + if (surf_type == "x-plane") { surfaces_c[i_surf] = new SurfaceXPlane(surf_node); - } else if (surf_type.compare("y-plane") == 0) { + } else if (surf_type == "y-plane") { surfaces_c[i_surf] = new SurfaceYPlane(surf_node); - } else if (surf_type.compare("z-plane") == 0) { + } else if (surf_type == "z-plane") { surfaces_c[i_surf] = new SurfaceZPlane(surf_node); - } else if (surf_type.compare("plane") == 0) { + } else if (surf_type == "plane") { surfaces_c[i_surf] = new SurfacePlane(surf_node); - } else if (surf_type.compare("x-cylinder") == 0) { + } else if (surf_type == "x-cylinder") { surfaces_c[i_surf] = new SurfaceXCylinder(surf_node); - } else if (surf_type.compare("y-cylinder") == 0) { + } else if (surf_type == "y-cylinder") { surfaces_c[i_surf] = new SurfaceYCylinder(surf_node); - } else if (surf_type.compare("z-cylinder") == 0) { + } else if (surf_type == "z-cylinder") { surfaces_c[i_surf] = new SurfaceZCylinder(surf_node); - } else if (surf_type.compare("sphere") == 0) { + } else if (surf_type == "sphere") { surfaces_c[i_surf] = new SurfaceSphere(surf_node); - } else if (surf_type.compare("x-cone") == 0) { + } else if (surf_type == "x-cone") { surfaces_c[i_surf] = new SurfaceXCone(surf_node); - } else if (surf_type.compare("y-cone") == 0) { + } else if (surf_type == "y-cone") { surfaces_c[i_surf] = new SurfaceYCone(surf_node); - } else if (surf_type.compare("z-cone") == 0) { + } else if (surf_type == "z-cone") { surfaces_c[i_surf] = new SurfaceZCone(surf_node); - } else if (surf_type.compare("quadric") == 0) { + } else if (surf_type == "quadric") { surfaces_c[i_surf] = new SurfaceQuadric(surf_node); } else { - std::string err_msg{"Invalid surface type, \""}; - err_msg += surf_type; - err_msg += "\""; + std::stringstream err_msg; + err_msg << "Invalid surface type, \"" << surf_type << "\""; fatal_error(err_msg); } } @@ -1124,15 +1117,15 @@ read_surfaces(pugi::xml_node *node) if (in_dict == surface_dict.end()) { surface_dict[id] = i_surf; } else { - std::string err_msg{"Two or more surfaces use the same unique ID: "}; - err_msg += std::to_string(id); + std::stringstream err_msg; + err_msg << "Two or more surfaces use the same unique ID: " << id; fatal_error(err_msg); } } // Find the global bounding box (of periodic BC surfaces). - double xmin{INFTY}, xmax{-INFTY}, ymin{INFTY}, ymax{-INFTY}, - zmin{INFTY}, zmax{-INFTY}; + double xmin {INFTY}, xmax {-INFTY}, ymin {INFTY}, ymax {-INFTY}, + zmin {INFTY}, zmax {-INFTY}; int i_xmin, i_xmax, i_ymin, i_ymax, i_zmin, i_zmax; for (int i_surf = 0; i_surf < n_surfaces; i_surf++) { if (surfaces_c[i_surf]->bc == BC_PERIODIC) { @@ -1141,15 +1134,16 @@ read_surfaces(pugi::xml_node *node) PeriodicSurface *surf = dynamic_cast(surf_base); // Make sure this surface inherits from PeriodicSurface. - if (surf == NULL) { - std::string err_msg{"Periodic boundary condition not supported for " - "surface "}; - err_msg += std::to_string(surf_base->id); - err_msg += ". Periodic BCs are only supported for planar surfaces."; + if (!surf) { + std::stringstream err_msg; + err_msg << "Periodic boundary condition not supported for surface " + << surf_base->id + << ". Periodic BCs are only supported for planar surfaces."; + fatal_error(err_msg); } // See if this surface makes part of the global bounding box. - struct BoundingBox bb = surf->bounding_box(); + BoundingBox bb = surf->bounding_box(); if (bb.xmin > -INFTY and bb.xmin < xmin) { xmin = bb.xmin; i_xmin = i_surf; @@ -1188,7 +1182,7 @@ read_surfaces(pugi::xml_node *node) // differently). SurfacePlane *surf_p = dynamic_cast(surf); - if (surf_p == NULL) { + if (!surf_p) { // This is not a SurfacePlane. if (surf->i_periodic == C_NONE) { // The user did not specify the matching periodic surface. See if we @@ -1217,9 +1211,9 @@ read_surfaces(pugi::xml_node *node) // This is a SurfacePlane. We won't try to find it's partner if the // user didn't specify one. if (surf->i_periodic == C_NONE) { - std::string err_msg{"No matching periodic surface specified for " - "periodic boundary condition on surface "}; - err_msg += std::to_string(surf->id); + std::stringstream err_msg; + err_msg << "No matching periodic surface specified for periodic " + "boundary condition on surface " << surf->id; fatal_error(err_msg); } else { // Convert the surface id to an index. @@ -1229,11 +1223,13 @@ read_surfaces(pugi::xml_node *node) // Make sure the opposite surface is also periodic. if (surfaces_c[surf->i_periodic]->bc != BC_PERIODIC) { - std::string err_msg{"Could not find matching surface for periodic " - "boundary condition on surface "}; - err_msg += std::to_string(surf->id); + std::stringstream err_msg; + err_msg << "Could not find matching surface for periodic boundary " + "condition on surface " << surf->id; fatal_error(err_msg); } } } } + +} // namespace openmc diff --git a/src/surface.h b/src/surface.h index 469d884862..72cfd62023 100644 --- a/src/surface.h +++ b/src/surface.h @@ -3,32 +3,37 @@ #include #include // For numeric_limits +#include #include "hdf5.h" #include "pugixml/pugixml.hpp" + +namespace openmc { + //============================================================================== // Module constants //============================================================================== -extern "C" const int BC_TRANSMIT{0}; -extern "C" const int BC_VACUUM{1}; -extern "C" const int BC_REFLECT{2}; -extern "C" const int BC_PERIODIC{3}; +extern "C" const int BC_TRANSMIT {0}; +extern "C" const int BC_VACUUM {1}; +extern "C" const int BC_REFLECT {2}; +extern "C" const int BC_PERIODIC {3}; //============================================================================== // Constants that should eventually be moved out of this file //============================================================================== extern "C" double FP_COINCIDENT; -const double INFTY{std::numeric_limits::max()}; -const int C_NONE{-1}; +constexpr double INFTY{std::numeric_limits::max()}; +constexpr int C_NONE {-1}; //============================================================================== // Global variables //============================================================================== -int n_surfaces{0}; +// Braces force n_surfaces to be defined here, not just declared. +extern "C" {int32_t n_surfaces {0};} class Surface; Surface **surfaces_c; @@ -64,6 +69,8 @@ public: Surface(pugi::xml_node surf_node); + virtual ~Surface() {} + //! Determine which side of a surface a point lies on. //! @param xyz[3] The 3D Cartesian coordinate of a point. //! @param uvw[3] A direction used to "break ties" and pick a sense when the @@ -411,9 +418,10 @@ extern "C" void free_memory_surfaces_c() { for (int i = 0; i < n_surfaces; i++) {delete surfaces_c[i];} delete surfaces_c; - surfaces_c = NULL; + surfaces_c = nullptr; n_surfaces = 0; surface_dict.clear(); } +} // namespace openmc #endif // SURFACE_H diff --git a/src/surface_header.F90 b/src/surface_header.F90 index 8985e8406e..9ed89a14e9 100644 --- a/src/surface_header.F90 +++ b/src/surface_header.F90 @@ -126,7 +126,7 @@ module surface_header end type Surface - integer(C_INT), bind(C) :: n_surfaces ! # of surfaces + integer(C_INT32_T), bind(C) :: n_surfaces ! # of surfaces type(Surface), allocatable, target :: surfaces(:) diff --git a/src/xml_interface.h b/src/xml_interface.h index fbc82e056b..778497562b 100644 --- a/src/xml_interface.h +++ b/src/xml_interface.h @@ -2,26 +2,23 @@ #define XML_INTERFACE_H #include // for std::transform +#include #include #include "pugixml/pugixml.hpp" +namespace openmc { + bool -check_for_node(const pugi::xml_node &node, const char *name) +check_for_node(pugi::xml_node node, const char *name) { - if (node.attribute(name)) { - return true; - } else if (node.child(name)) { - return true; - } else { - return false; - } + return node.attribute(name) || node.child(name); } std::string -get_node_value(const pugi::xml_node &node, const char *name) +get_node_value(pugi::xml_node node, const char *name) { // Search for either an attribute or child tag and get the data as a char*. const pugi::char_t *value_char; @@ -30,11 +27,9 @@ get_node_value(const pugi::xml_node &node, const char *name) } else if (node.child(name)) { value_char = node.child_value(name); } else { - std::string err_msg("Node \""); - err_msg += name; - err_msg += "\" is not a memeber of the \""; - err_msg += node.name(); - err_msg += "\" XML node"; + std::stringstream err_msg; + err_msg << "Node \"" << name << "\" is not a member of the \"" + << node.name() << "\" XML node"; fatal_error(err_msg); } @@ -49,4 +44,5 @@ get_node_value(const pugi::xml_node &node, const char *name) return value; } +} // namespace openmc #endif // XML_INTERFACE_H From 48ac683a0cec3724c80629ac549a0eb4a4f7b4d1 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Wed, 31 Jan 2018 17:52:52 -0500 Subject: [PATCH 033/212] Remove C++/Fortran interoperable "seed" --- openmc/capi/settings.py | 5 ++--- src/api.F90 | 10 +++++----- src/initialize.F90 | 3 +-- src/input_xml.F90 | 2 +- src/random_lcg.F90 | 13 ++++++++----- src/random_lcg.cpp | 5 +++-- src/random_lcg.h | 8 +++++++- src/state_point.F90 | 6 ++++-- tests/unit_tests/test_capi.py | 10 +++++----- 9 files changed, 36 insertions(+), 26 deletions(-) diff --git a/openmc/capi/settings.py b/openmc/capi/settings.py index eede6cf47b..1063d6463e 100644 --- a/openmc/capi/settings.py +++ b/openmc/capi/settings.py @@ -11,8 +11,7 @@ _RUN_MODES = {1: 'fixed source', 5: 'volume'} _dll.openmc_set_seed.argtypes = [c_int64] -_dll.openmc_set_seed.restype = c_int -_dll.openmc_set_seed.errcheck = _error_handler +_dll.openmc_get_seed.restype = c_int64 class _Settings(object): @@ -43,7 +42,7 @@ class _Settings(object): @property def seed(self): - return c_int64.in_dll(_dll, 'seed').value + return _dll.openmc_get_seed() @seed.setter def seed(self, seed): diff --git a/src/api.F90 b/src/api.F90 index 5d56b857ca..f07e5e38a5 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -18,7 +18,7 @@ module openmc_api use initialize, only: openmc_init use particle_header, only: Particle use plot, only: openmc_plot_geometry - use random_lcg, only: seed, openmc_set_seed + use random_lcg, only: openmc_get_seed, openmc_set_seed use settings use simulation_header use source_header, only: openmc_extend_sources, openmc_source_set_strength @@ -60,6 +60,7 @@ module openmc_api public :: openmc_get_filter_next_id public :: openmc_get_material_index public :: openmc_get_nuclide_index + public :: openmc_get_seed public :: openmc_get_tally_index public :: openmc_global_tallies public :: openmc_hard_reset @@ -79,6 +80,7 @@ module openmc_api public :: openmc_plot_geometry public :: openmc_reset public :: openmc_run + public :: openmc_set_seed public :: openmc_simulation_finalize public :: openmc_simulation_init public :: openmc_source_bank @@ -142,7 +144,7 @@ contains run_CE = .true. run_mode = NONE satisfy_triggers = .false. - seed = 1_8 + call openmc_set_seed(DEFAULT_SEED) source_latest = .false. source_separate = .false. source_write = .true. @@ -228,8 +230,6 @@ contains !=============================================================================== subroutine openmc_hard_reset() bind(C) - integer :: err - ! Reset all tallies and timers call openmc_reset() @@ -238,7 +238,7 @@ contains total_gen = 0 ! Reset the random number generator state - err = openmc_set_seed(1_8) + call openmc_set_seed(DEFAULT_SEED) end subroutine openmc_hard_reset !=============================================================================== diff --git a/src/initialize.F90 b/src/initialize.F90 index 2af93627ea..7b699b9cb7 100644 --- a/src/initialize.F90 +++ b/src/initialize.F90 @@ -44,7 +44,6 @@ contains subroutine openmc_init(intracomm) bind(C) integer, intent(in), optional :: intracomm ! MPI intracommunicator - integer :: err #ifdef _OPENMP character(MAX_WORD_LEN) :: envvar #endif @@ -95,7 +94,7 @@ contains ! Initialize random number generator -- if the user specifies a seed, it ! will be re-initialized later - err = openmc_set_seed(DEFAULT_SEED) + call openmc_set_seed(DEFAULT_SEED) ! Read XML input files call read_input_xml() diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 55eeca9e14..0b7790a51c 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -349,7 +349,7 @@ contains ! Copy random number seed if specified if (check_for_node(root, "seed")) then call get_node_value(root, "seed", seed) - err = openmc_set_seed(seed) + call openmc_set_seed(seed) end if ! Number of bins for logarithmic grid diff --git a/src/random_lcg.F90 b/src/random_lcg.F90 index 839bd729a9..d64717cf42 100644 --- a/src/random_lcg.F90 +++ b/src/random_lcg.F90 @@ -4,8 +4,6 @@ module random_lcg implicit none - integer(C_INT64_T), bind(C) :: seed - interface function prn() result(pseudo_rn) bind(C) use ISO_C_BINDING @@ -38,11 +36,16 @@ module random_lcg integer(C_INT), value :: n end subroutine prn_set_stream - function openmc_set_seed(new_seed) result(err) bind(C) + function openmc_get_seed() result(seed) bind(C) + use ISO_C_BINDING + implicit none + integer(C_INT64_T) :: seed + end function openmc_get_seed + + subroutine openmc_set_seed(new_seed) bind(C) use ISO_C_BINDING implicit none integer(C_INT64_T), value :: new_seed - integer(C_INT) :: err - end function openmc_set_seed + end subroutine openmc_set_seed end interface end module random_lcg diff --git a/src/random_lcg.cpp b/src/random_lcg.cpp index 2dcdd86a36..2a57316cb6 100644 --- a/src/random_lcg.cpp +++ b/src/random_lcg.cpp @@ -133,7 +133,9 @@ prn_set_stream(int i) // API FUNCTIONS //============================================================================== -extern "C" int +extern "C" int64_t openmc_get_seed() {return seed;} + +extern "C" void openmc_set_seed(int64_t new_seed) { seed = new_seed; @@ -144,7 +146,6 @@ openmc_set_seed(int64_t new_seed) } prn_set_stream(STREAM_TRACKING); } - return 0; } } // namespace openmc diff --git a/src/random_lcg.h b/src/random_lcg.h index cd065474ea..29b3fca47d 100644 --- a/src/random_lcg.h +++ b/src/random_lcg.h @@ -77,13 +77,19 @@ extern "C" void prn_set_stream(int n); // API FUNCTIONS //============================================================================== +//============================================================================== +//! Get OpenMC's master seed. +//============================================================================== + +extern "C" int64_t openmc_get_seed(); + //============================================================================== //! Set OpenMC's master seed. //! @param new_seed The master seed. All other seeds will be derived from this //! one. //============================================================================== -extern "C" int openmc_set_seed(int64_t new_seed); +extern "C" void openmc_set_seed(int64_t new_seed); } // namespace openmc #endif // RANDOM_LCG_H diff --git a/src/state_point.F90 b/src/state_point.F90 index ba7bcef19d..980a7333cd 100644 --- a/src/state_point.F90 +++ b/src/state_point.F90 @@ -26,7 +26,7 @@ module state_point use mgxs_header, only: nuclides_MG use nuclide_header, only: nuclides use output, only: time_stamp - use random_lcg, only: seed + use random_lcg, only: openmc_get_seed, openmc_set_seed use settings use simulation_header use string, only: to_str, count_digits, zero_padded, to_f_string @@ -97,7 +97,7 @@ contains call write_attribute(file_id, "path", path_input) ! Write out random number seed - call write_dataset(file_id, "seed", seed) + call write_dataset(file_id, "seed", openmc_get_seed()) ! Write run information if (run_CE) then @@ -642,6 +642,7 @@ contains integer :: n integer :: int_array(3) integer, allocatable :: array(:) + integer(C_INT64_T) :: seed integer(HID_T) :: file_id integer(HID_T) :: cmfd_group integer(HID_T) :: tallies_group @@ -672,6 +673,7 @@ contains ! Read and overwrite random number seed call read_dataset(seed, file_id, "seed") + call openmc_set_seed(seed) ! It is not impossible for a state point to be generated from a CE run but ! to be loaded in to an MG run (or vice versa), check to prevent that. diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index ba9ac5c9e0..cd24314ad3 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -29,11 +29,11 @@ def pincell_model(): yield # Delete generated files - files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', - 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] - for f in files: - if os.path.exists(f): - os.remove(f) + #files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', + # 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] + #for f in files: + # if os.path.exists(f): + # os.remove(f) @pytest.fixture(scope='module') From 7acf3f91dbb74c7ca0aad9bedfc2cdc14c2c2463 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Fri, 2 Feb 2018 19:56:23 -0500 Subject: [PATCH 034/212] Address #959 comments --- src/surface.cpp | 2 +- src/surface.h | 38 +++++++++++++++++------------------ tests/unit_tests/test_capi.py | 10 ++++----- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/surface.cpp b/src/surface.cpp index 16f333f7e1..9abfd23d2e 100644 --- a/src/surface.cpp +++ b/src/surface.cpp @@ -1,12 +1,12 @@ #include "surface.h" #include +#include #include #include "error.h" #include "hdf5_interface.h" #include "xml_interface.h" -#include namespace openmc { diff --git a/src/surface.h b/src/surface.h index 72cfd62023..627a8fbae2 100644 --- a/src/surface.h +++ b/src/surface.h @@ -67,7 +67,7 @@ public: int bc; //!< Boundary condition std::string name{""}; //!< User-defined name - Surface(pugi::xml_node surf_node); + explicit Surface(pugi::xml_node surf_node); virtual ~Surface() {} @@ -127,7 +127,7 @@ class PeriodicSurface : public Surface public: int i_periodic{C_NONE}; //!< Index of corresponding periodic surface - PeriodicSurface(pugi::xml_node surf_node); + explicit PeriodicSurface(pugi::xml_node surf_node); //! Translate a particle onto this surface from a periodic partner surface. //! @param other A pointer to the partner surface in this periodic BC. @@ -141,7 +141,7 @@ public: double uvw[3]) const = 0; //! Get the bounding box for this surface. - virtual struct BoundingBox bounding_box() const = 0; + virtual BoundingBox bounding_box() const = 0; }; //============================================================================== @@ -154,7 +154,7 @@ class SurfaceXPlane : public PeriodicSurface { double x0; public: - SurfaceXPlane(pugi::xml_node surf_node); + explicit SurfaceXPlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -162,7 +162,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; - struct BoundingBox bounding_box() const; + BoundingBox bounding_box() const; }; //============================================================================== @@ -175,7 +175,7 @@ class SurfaceYPlane : public PeriodicSurface { double y0; public: - SurfaceYPlane(pugi::xml_node surf_node); + explicit SurfaceYPlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -183,7 +183,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; - struct BoundingBox bounding_box() const; + BoundingBox bounding_box() const; }; //============================================================================== @@ -196,7 +196,7 @@ class SurfaceZPlane : public PeriodicSurface { double z0; public: - SurfaceZPlane(pugi::xml_node surf_node); + explicit SurfaceZPlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -204,7 +204,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; - struct BoundingBox bounding_box() const; + BoundingBox bounding_box() const; }; //============================================================================== @@ -217,7 +217,7 @@ class SurfacePlane : public PeriodicSurface { double A, B, C, D; public: - SurfacePlane(pugi::xml_node surf_node); + explicit SurfacePlane(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -225,7 +225,7 @@ public: void to_hdf5_inner(hid_t group_id) const; bool periodic_translate(PeriodicSurface *other, double xyz[3], double uvw[3]) const; - struct BoundingBox bounding_box() const; + BoundingBox bounding_box() const; }; //============================================================================== @@ -239,7 +239,7 @@ class SurfaceXCylinder : public Surface { double y0, z0, r; public: - SurfaceXCylinder(pugi::xml_node surf_node); + explicit SurfaceXCylinder(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -258,7 +258,7 @@ class SurfaceYCylinder : public Surface { double x0, z0, r; public: - SurfaceYCylinder(pugi::xml_node surf_node); + explicit SurfaceYCylinder(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -277,7 +277,7 @@ class SurfaceZCylinder : public Surface { double x0, y0, r; public: - SurfaceZCylinder(pugi::xml_node surf_node); + explicit SurfaceZCylinder(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -296,7 +296,7 @@ class SurfaceSphere : public Surface { double x0, y0, z0, r; public: - SurfaceSphere(pugi::xml_node surf_node); + explicit SurfaceSphere(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -315,7 +315,7 @@ class SurfaceXCone : public Surface { double x0, y0, z0, r_sq; public: - SurfaceXCone(pugi::xml_node surf_node); + explicit SurfaceXCone(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -334,7 +334,7 @@ class SurfaceYCone : public Surface { double x0, y0, z0, r_sq; public: - SurfaceYCone(pugi::xml_node surf_node); + explicit SurfaceYCone(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -353,7 +353,7 @@ class SurfaceZCone : public Surface { double x0, y0, z0, r_sq; public: - SurfaceZCone(pugi::xml_node surf_node); + explicit SurfaceZCone(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; @@ -372,7 +372,7 @@ class SurfaceQuadric : public Surface // Ax^2 + By^2 + Cz^2 + Dxy + Eyz + Fxz + Gx + Hy + Jz + K = 0 double A, B, C, D, E, F, G, H, J, K; public: - SurfaceQuadric(pugi::xml_node surf_node); + explicit SurfaceQuadric(pugi::xml_node surf_node); double evaluate(const double xyz[3]) const; double distance(const double xyz[3], const double uvw[3], bool coincident) const; diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index cd24314ad3..ba9ac5c9e0 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -29,11 +29,11 @@ def pincell_model(): yield # Delete generated files - #files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', - # 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] - #for f in files: - # if os.path.exists(f): - # os.remove(f) + files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', + 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] + for f in files: + if os.path.exists(f): + os.remove(f) @pytest.fixture(scope='module') From cb076c8e4fa81b45e09de37be41362cf17c1d1c9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 3 Feb 2018 12:38:01 -0600 Subject: [PATCH 035/212] Update ifdef for MPI F08 --- src/simulation.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/simulation.F90 b/src/simulation.F90 index faf3c4016a..424c55e9bd 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -475,7 +475,7 @@ contains integer :: count_per_filter ! number of result values for one filter bin integer(8) :: temp real(8) :: tempr(3) ! temporary array for communication -#ifdef MPIF08 +#ifdef OPENMC_MPIF08 type(MPI_Datatype) :: result_block #else integer :: result_block From 9149e0e0ef3420049a64bb03a515c9d01b03e483 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Sun, 4 Feb 2018 15:39:54 -0500 Subject: [PATCH 036/212] Moved cross_sections.F90 functionality into Material and Nuclide --- CMakeLists.txt | 1 - src/cross_section.F90 | 936 ---------------------------------------- src/material_header.F90 | 111 +++++ src/mgxs_header.F90 | 21 +- src/nuclide_header.F90 | 764 +++++++++++++++++++++++++++++++- src/physics.F90 | 3 +- src/sab_header.F90 | 103 ++++- src/tallies/tally.F90 | 5 +- src/tracking.F90 | 45 +- 9 files changed, 1006 insertions(+), 983 deletions(-) delete mode 100644 src/cross_section.F90 diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f5b2168fe..cf44c500ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -347,7 +347,6 @@ set(LIBOPENMC_FORTRAN_SRC src/cmfd_prod_operator.F90 src/cmfd_solver.F90 src/constants.F90 - src/cross_section.F90 src/dict_header.F90 src/distribution_multivariate.F90 src/distribution_univariate.F90 diff --git a/src/cross_section.F90 b/src/cross_section.F90 deleted file mode 100644 index 47e1c4fc5d..0000000000 --- a/src/cross_section.F90 +++ /dev/null @@ -1,936 +0,0 @@ -module cross_section - - use algorithm, only: binary_search - use constants - use error, only: fatal_error - use list_header, only: ListElemInt - use material_header, only: Material, materials - use math, only: faddeeva, w_derivative, broaden_wmp_polynomials - use multipole_header, only: FORM_RM, FORM_MLBW, MP_EA, RM_RT, RM_RA, RM_RF, & - MLBW_RT, MLBW_RX, MLBW_RA, MLBW_RF, FIT_T, FIT_A,& - FIT_F, MultipoleArray - use nuclide_header - use particle_header, only: Particle - use random_lcg, only: prn, future_prn, prn_set_stream - use sab_header, only: SAlphaBeta, sab_tables - use settings - use simulation_header - use tally_header, only: active_tallies - - implicit none - -contains - -!=============================================================================== -! CALCULATE_XS determines the macroscopic cross sections for the material the -! particle is currently traveling through. -!=============================================================================== - - subroutine calculate_xs(p) - - type(Particle), intent(inout) :: p - - integer :: i ! loop index over nuclides - integer :: i_nuclide ! index into nuclides array - integer :: i_sab ! index into sab_tables array - integer :: j ! index in mat % i_sab_nuclides - integer :: i_grid ! index into logarithmic mapping array or material - ! union grid - real(8) :: atom_density ! atom density of a nuclide - real(8) :: sab_frac ! fraction of atoms affected by S(a,b) - logical :: check_sab ! should we check for S(a,b) table? - - ! Set all material macroscopic cross sections to zero - material_xs % total = ZERO - material_xs % absorption = ZERO - material_xs % fission = ZERO - material_xs % nu_fission = ZERO - - ! Exit subroutine if material is void - if (p % material == MATERIAL_VOID) return - - associate (mat => materials(p % material)) - ! Find energy index on energy grid - i_grid = int(log(p % E/energy_min_neutron)/log_spacing) - - ! Determine if this material has S(a,b) tables - check_sab = (mat % n_sab > 0) - - ! Initialize position in i_sab_nuclides - j = 1 - - ! Add contribution from each nuclide in material - do i = 1, mat % n_nuclides - ! ====================================================================== - ! CHECK FOR S(A,B) TABLE - - i_sab = 0 - sab_frac = ZERO - - ! Check if this nuclide matches one of the S(a,b) tables specified. - ! This relies on i_sab_nuclides being in sorted order - if (check_sab) then - if (i == mat % i_sab_nuclides(j)) then - ! Get index in sab_tables - i_sab = mat % i_sab_tables(j) - sab_frac = mat % sab_fracs(j) - - ! If particle energy is greater than the highest energy for the - ! S(a,b) table, then don't use the S(a,b) table - if (p % E > sab_tables(i_sab) % data(1) % threshold_inelastic) then - i_sab = 0 - end if - - ! Increment position in i_sab_nuclides - j = j + 1 - - ! Don't check for S(a,b) tables if there are no more left - if (j > size(mat % i_sab_tables)) check_sab = .false. - end if - end if - - ! ====================================================================== - ! CALCULATE MICROSCOPIC CROSS SECTION - - ! Determine microscopic cross sections for this nuclide - i_nuclide = mat % nuclide(i) - - ! Calculate microscopic cross section for this nuclide - if (p % E /= micro_xs(i_nuclide) % last_E & - .or. p % sqrtkT /= micro_xs(i_nuclide) % last_sqrtkT & - .or. i_sab /= micro_xs(i_nuclide) % index_sab & - .or. sab_frac /= micro_xs(i_nuclide) % sab_frac) then - call calculate_nuclide_xs(i_nuclide, i_sab, p % E, i_grid, & - p % sqrtkT, sab_frac) - end if - - ! ====================================================================== - ! ADD TO MACROSCOPIC CROSS SECTION - - ! Copy atom density of nuclide in material - atom_density = mat % atom_density(i) - - ! Add contributions to material macroscopic total cross section - material_xs % total = material_xs % total + & - atom_density * micro_xs(i_nuclide) % total - - ! Add contributions to material macroscopic absorption cross section - material_xs % absorption = material_xs % absorption + & - atom_density * micro_xs(i_nuclide) % absorption - - ! Add contributions to material macroscopic fission cross section - material_xs % fission = material_xs % fission + & - atom_density * micro_xs(i_nuclide) % fission - - ! Add contributions to material macroscopic nu-fission cross section - material_xs % nu_fission = material_xs % nu_fission + & - atom_density * micro_xs(i_nuclide) % nu_fission - end do - end associate - - end subroutine calculate_xs - -!=============================================================================== -! CALCULATE_NUCLIDE_XS determines microscopic cross sections for a nuclide of a -! given index in the nuclides array at the energy of the given particle -!=============================================================================== - - subroutine calculate_nuclide_xs(i_nuclide, i_sab, E, i_log_union, sqrtkT, & - sab_frac) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_sab ! index into sab_tables array - real(8), intent(in) :: E ! energy - integer, intent(in) :: i_log_union ! index into logarithmic mapping array or - ! material union energy grid - real(8), intent(in) :: sqrtkT ! square root of kT, material dependent - real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) - - logical :: use_mp ! true if XS can be calculated with windowed multipole - integer :: i_temp ! index for temperature - integer :: i_grid ! index on nuclide energy grid - integer :: i_low ! lower logarithmic mapping index - integer :: i_high ! upper logarithmic mapping index - integer :: i_rxn ! reaction index - integer :: j ! index in DEPLETION_RX - real(8) :: f ! interp factor on nuclide energy grid - real(8) :: kT ! temperature in eV - real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables - - ! Initialize cached cross sections to zero - micro_xs(i_nuclide) % elastic = CACHE_INVALID - micro_xs(i_nuclide) % thermal = ZERO - micro_xs(i_nuclide) % thermal_elastic = ZERO - - associate (nuc => nuclides(i_nuclide)) - ! Check to see if there is multipole data present at this energy - use_mp = .false. - if (nuc % mp_present) then - if (E >= nuc % multipole % start_E .and. & - E <= nuc % multipole % end_E) then - use_mp = .true. - end if - end if - - ! Evaluate multipole or interpolate - if (use_mp) then - ! Call multipole kernel - call multipole_eval(nuc % multipole, E, sqrtkT, sig_t, sig_a, sig_f) - - micro_xs(i_nuclide) % total = sig_t - micro_xs(i_nuclide) % absorption = sig_a - micro_xs(i_nuclide) % fission = sig_f - - if (nuc % fissionable) then - micro_xs(i_nuclide) % nu_fission = sig_f * nuc % nu(E, EMISSION_TOTAL) - else - micro_xs(i_nuclide) % nu_fission = ZERO - end if - - if (need_depletion_rx) then - ! Initialize all reaction cross sections to zero - micro_xs(i_nuclide) % reaction(:) = ZERO - - ! Only non-zero reaction is (n,gamma) - micro_xs(i_nuclide) % reaction(4) = sig_a - sig_f - end if - - ! Ensure these values are set - ! Note, the only time either is used is in one of 4 places: - ! 1. physics.F90 - scatter - For inelastic scatter. - ! 2. physics.F90 - sample_fission - For partial fissions. - ! 3. tally.F90 - score_general - For tallying on MTxxx reactions. - ! 4. cross_section.F90 - calculate_urr_xs - For unresolved purposes. - ! It is worth noting that none of these occur in the resolved - ! resonance range, so the value here does not matter. index_temp is - ! set to -1 to force a segfault in case a developer messes up and tries - ! to use it with multipole. - micro_xs(i_nuclide) % index_temp = -1 - micro_xs(i_nuclide) % index_grid = 0 - micro_xs(i_nuclide) % interp_factor = ZERO - - else - ! Find the appropriate temperature index. - kT = sqrtkT**2 - select case (temperature_method) - case (TEMPERATURE_NEAREST) - i_temp = minloc(abs(nuclides(i_nuclide) % kTs - kT), dim=1) - - case (TEMPERATURE_INTERPOLATION) - ! Find temperatures that bound the actual temperature - do i_temp = 1, size(nuc % kTs) - 1 - if (nuc % kTs(i_temp) <= kT .and. kT < nuc % kTs(i_temp + 1)) exit - end do - - ! Randomly sample between temperature i and i+1 - f = (kT - nuc % kTs(i_temp)) / & - (nuc % kTs(i_temp + 1) - nuc % kTs(i_temp)) - if (f > prn()) i_temp = i_temp + 1 - end select - - associate (grid => nuc % grid(i_temp), xs => nuc % xs(i_temp)) - ! Determine the energy grid index using a logarithmic mapping to - ! reduce the energy range over which a binary search needs to be - ! performed - - if (E < grid % energy(1)) then - i_grid = 1 - elseif (E > grid % energy(size(grid % energy))) then - i_grid = size(grid % energy) - 1 - else - ! Determine bounding indices based on which equal log-spaced - ! interval the energy is in - i_low = grid % grid_index(i_log_union) - i_high = grid % grid_index(i_log_union + 1) + 1 - - ! Perform binary search over reduced range - i_grid = binary_search(grid % energy(i_low:i_high), & - i_high - i_low + 1, E) + i_low - 1 - end if - - ! check for rare case where two energy points are the same - if (grid % energy(i_grid) == grid % energy(i_grid + 1)) & - i_grid = i_grid + 1 - - ! calculate interpolation factor - f = (E - grid % energy(i_grid)) / & - (grid % energy(i_grid + 1) - grid % energy(i_grid)) - - micro_xs(i_nuclide) % index_temp = i_temp - micro_xs(i_nuclide) % index_grid = i_grid - micro_xs(i_nuclide) % interp_factor = f - - ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % total = (ONE - f) * xs % value(XS_TOTAL,i_grid) & - + f * xs % value(XS_TOTAL,i_grid + 1) - - ! Calculate microscopic nuclide absorption cross section - micro_xs(i_nuclide) % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & - i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) - - if (nuc % fissionable) then - ! Calculate microscopic nuclide total cross section - micro_xs(i_nuclide) % fission = (ONE - f) * xs % value(XS_FISSION,i_grid) & - + f * xs % value(XS_FISSION,i_grid + 1) - - ! Calculate microscopic nuclide nu-fission cross section - micro_xs(i_nuclide) % nu_fission = (ONE - f) * xs % value(XS_NU_FISSION, & - i_grid) + f * xs % value(XS_NU_FISSION,i_grid + 1) - else - micro_xs(i_nuclide) % fission = ZERO - micro_xs(i_nuclide) % nu_fission = ZERO - end if - end associate - - ! Depletion-related reactions - if (need_depletion_rx) then - do j = 1, 6 - ! Initialize reaction xs to zero - micro_xs(i_nuclide) % reaction(j) = ZERO - - ! If reaction is present and energy is greater than threshold, set - ! the reaction xs appropriately - i_rxn = nuc % reaction_index(DEPLETION_RX(j)) - if (i_rxn > 0) then - associate (xs => nuc % reactions(i_rxn) % xs(i_temp)) - if (i_grid >= xs % threshold) then - micro_xs(i_nuclide) % reaction(j) = (ONE - f) * & - xs % value(i_grid - xs % threshold + 1) + & - f * xs % value(i_grid - xs % threshold + 2) - end if - end associate - end if - end do - end if - - end if - - ! Initialize sab treatment to false - micro_xs(i_nuclide) % index_sab = NONE - micro_xs(i_nuclide) % sab_frac = ZERO - - ! Initialize URR probability table treatment to false - micro_xs(i_nuclide) % use_ptable = .false. - - ! If there is S(a,b) data for this nuclide, we need to set the sab_scatter - ! and sab_elastic cross sections and correct the total and elastic cross - ! sections. - - if (i_sab > 0) then - call calculate_sab_xs(i_nuclide, i_sab, E, sqrtkT, sab_frac) - end if - - ! If the particle is in the unresolved resonance range and there are - ! probability tables, we need to determine cross sections from the table - - if (urr_ptables_on .and. nuc % urr_present .and. .not. use_mp) then - if (E > nuc % urr_data(i_temp) % energy(1) .and. E < nuc % & - urr_data(i_temp) % energy(nuc % urr_data(i_temp) % n_energy)) then - call calculate_urr_xs(i_nuclide, i_temp, E) - end if - end if - - micro_xs(i_nuclide) % last_E = E - micro_xs(i_nuclide) % last_sqrtkT = sqrtkT - end associate - - end subroutine calculate_nuclide_xs - -!=============================================================================== -! CALCULATE_SAB_XS determines the elastic and inelastic scattering -! cross-sections in the thermal energy range. These cross sections replace a -! fraction of whatever data were taken from the normal Nuclide table. -!=============================================================================== - - subroutine calculate_sab_xs(i_nuclide, i_sab, E, sqrtkT, sab_frac) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_sab ! index into sab_tables array - real(8), intent(in) :: E ! energy - real(8), intent(in) :: sqrtkT ! temperature - real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) - - integer :: i_grid ! index on S(a,b) energy grid - integer :: i_temp ! temperature index - real(8) :: f ! interp factor on S(a,b) energy grid - real(8) :: inelastic ! S(a,b) inelastic cross section - real(8) :: elastic ! S(a,b) elastic cross section - real(8) :: kT - - ! Set flag that S(a,b) treatment should be used for scattering - micro_xs(i_nuclide) % index_sab = i_sab - - ! Determine temperature for S(a,b) table - kT = sqrtkT**2 - if (temperature_method == TEMPERATURE_NEAREST) then - ! If using nearest temperature, do linear search on temperature - do i_temp = 1, size(sab_tables(i_sab) % kTs) - if (abs(sab_tables(i_sab) % kTs(i_temp) - kT) < & - K_BOLTZMANN*temperature_tolerance) exit - end do - else - ! Find temperatures that bound the actual temperature - do i_temp = 1, size(sab_tables(i_sab) % kTs) - 1 - if (sab_tables(i_sab) % kTs(i_temp) <= kT .and. & - kT < sab_tables(i_sab) % kTs(i_temp + 1)) exit - end do - - ! Randomly sample between temperature i and i+1 - f = (kT - sab_tables(i_sab) % kTs(i_temp)) / & - (sab_tables(i_sab) % kTs(i_temp + 1) & - - sab_tables(i_sab) % kTs(i_temp)) - if (f > prn()) i_temp = i_temp + 1 - end if - - - ! Get pointer to S(a,b) table - associate (sab => sab_tables(i_sab) % data(i_temp)) - - ! Get index and interpolation factor for inelastic grid - if (E < sab % inelastic_e_in(1)) then - i_grid = 1 - f = ZERO - else - i_grid = binary_search(sab % inelastic_e_in, sab % n_inelastic_e_in, E) - f = (E - sab%inelastic_e_in(i_grid)) / & - (sab%inelastic_e_in(i_grid+1) - sab%inelastic_e_in(i_grid)) - end if - - ! Calculate S(a,b) inelastic scattering cross section - inelastic = (ONE - f) * sab % inelastic_sigma(i_grid) + & - f * sab % inelastic_sigma(i_grid + 1) - - ! Check for elastic data - if (E < sab % threshold_elastic) then - ! Determine whether elastic scattering is given in the coherent or - ! incoherent approximation. For coherent, the cross section is - ! represented as P/E whereas for incoherent, it is simply P - - if (sab % elastic_mode == SAB_ELASTIC_EXACT) then - if (E < sab % elastic_e_in(1)) then - ! If energy is below that of the lowest Bragg peak, the elastic - ! cross section will be zero - elastic = ZERO - else - i_grid = binary_search(sab % elastic_e_in, & - sab % n_elastic_e_in, E) - elastic = sab % elastic_P(i_grid) / E - end if - else - ! Determine index on elastic energy grid - if (E < sab % elastic_e_in(1)) then - i_grid = 1 - else - i_grid = binary_search(sab % elastic_e_in, & - sab % n_elastic_e_in, E) - end if - - ! Get interpolation factor for elastic grid - f = (E - sab%elastic_e_in(i_grid))/(sab%elastic_e_in(i_grid+1) - & - sab%elastic_e_in(i_grid)) - - ! Calculate S(a,b) elastic scattering cross section - elastic = (ONE - f) * sab % elastic_P(i_grid) + & - f * sab % elastic_P(i_grid + 1) - end if - else - ! No elastic data - elastic = ZERO - end if - end associate - - ! Store the S(a,b) cross sections. - micro_xs(i_nuclide) % thermal = sab_frac * (elastic + inelastic) - micro_xs(i_nuclide) % thermal_elastic = sab_frac * elastic - - ! Calculate free atom elastic cross section - call calculate_elastic_xs(i_nuclide) - - ! Correct total and elastic cross sections - micro_xs(i_nuclide) % total = micro_xs(i_nuclide) % total & - + micro_xs(i_nuclide) % thermal & - - sab_frac * micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % thermal & - + (ONE - sab_frac) * micro_xs(i_nuclide) % elastic - - ! Save temperature index and thermal fraction - micro_xs(i_nuclide) % index_temp_sab = i_temp - micro_xs(i_nuclide) % sab_frac = sab_frac - - end subroutine calculate_sab_xs - -!=============================================================================== -! CALCULATE_URR_XS determines cross sections in the unresolved resonance range -! from probability tables -!=============================================================================== - - subroutine calculate_urr_xs(i_nuclide, i_temp, E) - integer, intent(in) :: i_nuclide ! index into nuclides array - integer, intent(in) :: i_temp ! temperature index - real(8), intent(in) :: E ! energy - - integer :: i_energy ! index for energy - integer :: i_low ! band index at lower bounding energy - integer :: i_up ! band index at upper bounding energy - real(8) :: f ! interpolation factor - real(8) :: r ! pseudo-random number - real(8) :: elastic ! elastic cross section - real(8) :: capture ! (n,gamma) cross section - real(8) :: fission ! fission cross section - real(8) :: inelastic ! inelastic cross section - - micro_xs(i_nuclide) % use_ptable = .true. - - associate (nuc => nuclides(i_nuclide), urr => nuclides(i_nuclide) % urr_data(i_temp)) - ! determine energy table - i_energy = 1 - do - if (E < urr % energy(i_energy + 1)) exit - i_energy = i_energy + 1 - end do - - ! determine interpolation factor on table - f = (E - urr % energy(i_energy)) / & - (urr % energy(i_energy + 1) - urr % energy(i_energy)) - - ! sample probability table using the cumulative distribution - - ! Random numbers for xs calculation are sampled from a separated stream. - ! This guarantees the randomness and, at the same time, makes sure we reuse - ! random number for the same nuclide at different temperatures, therefore - ! preserving correlation of temperature in probability tables. - call prn_set_stream(STREAM_URR_PTABLE) - r = future_prn(int(i_nuclide, 8)) - call prn_set_stream(STREAM_TRACKING) - - i_low = 1 - do - if (urr % prob(i_energy, URR_CUM_PROB, i_low) > r) exit - i_low = i_low + 1 - end do - i_up = 1 - do - if (urr % prob(i_energy + 1, URR_CUM_PROB, i_up) > r) exit - i_up = i_up + 1 - end do - - ! determine elastic, fission, and capture cross sections from probability - ! table - if (urr % interp == LINEAR_LINEAR) then - elastic = (ONE - f) * urr % prob(i_energy, URR_ELASTIC, i_low) + & - f * urr % prob(i_energy + 1, URR_ELASTIC, i_up) - fission = (ONE - f) * urr % prob(i_energy, URR_FISSION, i_low) + & - f * urr % prob(i_energy + 1, URR_FISSION, i_up) - capture = (ONE - f) * urr % prob(i_energy, URR_N_GAMMA, i_low) + & - f * urr % prob(i_energy + 1, URR_N_GAMMA, i_up) - elseif (urr % interp == LOG_LOG) then - ! Get logarithmic interpolation factor - f = log(E / urr % energy(i_energy)) / & - log(urr % energy(i_energy + 1) / urr % energy(i_energy)) - - ! Calculate elastic cross section/factor - elastic = ZERO - if (urr % prob(i_energy, URR_ELASTIC, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_ELASTIC, i_up) > ZERO) then - elastic = exp((ONE - f) * log(urr % prob(i_energy, URR_ELASTIC, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_ELASTIC, & - i_up))) - end if - - ! Calculate fission cross section/factor - fission = ZERO - if (urr % prob(i_energy, URR_FISSION, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_FISSION, i_up) > ZERO) then - fission = exp((ONE - f) * log(urr % prob(i_energy, URR_FISSION, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_FISSION, & - i_up))) - end if - - ! Calculate capture cross section/factor - capture = ZERO - if (urr % prob(i_energy, URR_N_GAMMA, i_low) > ZERO .and. & - urr % prob(i_energy + 1, URR_N_GAMMA, i_up) > ZERO) then - capture = exp((ONE - f) * log(urr % prob(i_energy, URR_N_GAMMA, & - i_low)) + f * log(urr % prob(i_energy + 1, URR_N_GAMMA, & - i_up))) - end if - end if - - ! Determine treatment of inelastic scattering - inelastic = ZERO - if (urr % inelastic_flag > 0) then - ! Get index on energy grid and interpolation factor - i_energy = micro_xs(i_nuclide) % index_grid - f = micro_xs(i_nuclide) % interp_factor - - ! Determine inelastic scattering cross section - associate (xs => nuc % reactions(nuc % urr_inelastic) % xs(i_temp)) - if (i_energy >= xs % threshold) then - inelastic = (ONE - f) * xs % value(i_energy - xs % threshold + 1) + & - f * xs % value(i_energy - xs % threshold + 2) - end if - end associate - end if - - ! Multiply by smooth cross-section if needed - if (urr % multiply_smooth) then - call calculate_elastic_xs(i_nuclide) - elastic = elastic * micro_xs(i_nuclide) % elastic - capture = capture * (micro_xs(i_nuclide) % absorption - & - micro_xs(i_nuclide) % fission) - fission = fission * micro_xs(i_nuclide) % fission - end if - - ! Check for negative values - if (elastic < ZERO) elastic = ZERO - if (fission < ZERO) fission = ZERO - if (capture < ZERO) capture = ZERO - - ! Set elastic, absorption, fission, and total cross sections. Note that the - ! total cross section is calculated as sum of partials rather than using the - ! table-provided value - micro_xs(i_nuclide) % elastic = elastic - micro_xs(i_nuclide) % absorption = capture + fission - micro_xs(i_nuclide) % fission = fission - micro_xs(i_nuclide) % total = elastic + inelastic + capture + fission - - ! Determine nu-fission cross section - if (nuc % fissionable) then - micro_xs(i_nuclide) % nu_fission = nuc % nu(E, EMISSION_TOTAL) * & - micro_xs(i_nuclide) % fission - end if - end associate - - end subroutine calculate_urr_xs - -!=============================================================================== -! CALCULATE_ELASTIC_XS precalculates the free atom elastic scattering cross -! section. Normally it is not needed until a collision actually occurs in a -! material. However, in the thermal and unresolved resonance regions, we have to -! calculate it early to adjust the total cross section correctly. -!=============================================================================== - - subroutine calculate_elastic_xs(i_nuclide) - integer, intent(in) :: i_nuclide - - integer :: i_temp - integer :: i_grid - real(8) :: f - - ! Get temperature index, grid index, and interpolation factor - i_temp = micro_xs(i_nuclide) % index_temp - i_grid = micro_xs(i_nuclide) % index_grid - f = micro_xs(i_nuclide) % interp_factor - - if (i_temp > 0) then - associate (xs => nuclides(i_nuclide) % reactions(1) % xs(i_temp) % value) - micro_xs(i_nuclide) % elastic = (ONE - f)*xs(i_grid) + f*xs(i_grid + 1) - end associate - else - ! For multipole, elastic is total - absorption - micro_xs(i_nuclide) % elastic = micro_xs(i_nuclide) % total - & - micro_xs(i_nuclide) % absorption - end if - end subroutine calculate_elastic_xs - -!=============================================================================== -! MULTIPOLE_EVAL evaluates the windowed multipole equations for cross -! sections in the resolved resonance regions -!=============================================================================== - - subroutine multipole_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) - type(MultipoleArray), intent(in) :: multipole ! The windowed multipole - ! object to process. - real(8), intent(in) :: E ! The energy at which to - ! evaluate the cross section - real(8), intent(in) :: sqrtkT ! The temperature in the form - ! sqrt(kT), at which - ! to evaluate the XS. - real(8), intent(out) :: sig_t ! Total cross section - real(8), intent(out) :: sig_a ! Absorption cross section - real(8), intent(out) :: sig_f ! Fission cross section - complex(8) :: psi_chi ! The value of the psi-chi function for the - ! asymptotic form - complex(8) :: c_temp ! complex temporary variable - complex(8) :: w_val ! The faddeeva function evaluated at Z - complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) - complex(8) :: sig_t_factor(multipole % num_l) - real(8) :: broadened_polynomials(multipole % fit_order + 1) - real(8) :: sqrtE ! sqrt(E), eV - real(8) :: invE ! 1/E, eV - real(8) :: dopp ! sqrt(atomic weight ratio / kT) = 1 / (2 sqrt(xi)) - real(8) :: temp ! real temporary value - integer :: i_pole ! index of pole - integer :: i_poly ! index of curvefit - integer :: i_window ! index of window - integer :: startw ! window start pointer (for poles) - integer :: endw ! window end pointer - - ! ========================================================================== - ! Bookkeeping - - ! Define some frequently used variables. - sqrtE = sqrt(E) - invE = ONE / E - - ! Locate us. - i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & - + ONE) - startw = multipole % w_start(i_window) - endw = multipole % w_end(i_window) - - ! Fill in factors. - if (startw <= endw) then - call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - end if - - ! Initialize the ouptut cross sections. - sig_t = ZERO - sig_a = ZERO - sig_f = ZERO - - ! ========================================================================== - ! Add the contribution from the curvefit polynomial. - - if (sqrtkT /= ZERO .and. multipole % broaden_poly(i_window) == 1) then - ! Broaden the curvefit. - dopp = multipole % sqrtAWR / sqrtkT - call broaden_wmp_polynomials(E, dopp, multipole % fit_order + 1, & - broadened_polynomials) - do i_poly = 1, multipole % fit_order+1 - sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) & - * broadened_polynomials(i_poly) - sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) & - * broadened_polynomials(i_poly) - if (multipole % fissionable) then - sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) & - * broadened_polynomials(i_poly) - end if - end do - else ! Evaluate as if it were a polynomial - temp = invE - do i_poly = 1, multipole % fit_order+1 - sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) * temp - sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) * temp - if (multipole % fissionable) then - sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) * temp - end if - temp = temp * sqrtE - end do - end if - - ! ========================================================================== - ! Add the contribution from the poles in this window. - - if (sqrtkT == ZERO) then - ! If at 0K, use asymptotic form. - do i_pole = startw, endw - psi_chi = -ONEI / (multipole % data(MP_EA, i_pole) - sqrtE) - c_temp = psi_chi / E - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real(multipole % data(MLBW_RT, i_pole) * c_temp * & - sig_t_factor(multipole % l_value(i_pole))) & - + real(multipole % data(MLBW_RX, i_pole) * c_temp) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * c_temp) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * c_temp) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * c_temp * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * c_temp) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * c_temp) - end if - end if - end do - else - ! At temperature, use Faddeeva function-based form. - dopp = multipole % sqrtAWR / sqrtkT - if (endw >= startw) then - do i_pole = startw, endw - Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp - w_val = faddeeva(Z) * dopp * invE * SQRT_PI - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & - sig_t_factor(multipole % l_value(i_pole)) + & - multipole % data(MLBW_RX, i_pole)) * w_val) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) - end if - end if - end do - end if - end if - end subroutine multipole_eval - -!=============================================================================== -! MULTIPOLE_DERIV_EVAL evaluates the windowed multipole equations for the -! derivative of cross sections in the resolved resonance regions with respect to -! temperature. -!=============================================================================== - - subroutine multipole_deriv_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) - type(MultipoleArray), intent(in) :: multipole ! The windowed multipole - ! object to process. - real(8), intent(in) :: E ! The energy at which to - ! evaluate the cross section - real(8), intent(in) :: sqrtkT ! The temperature in the form - ! sqrt(kT), at which to - ! evaluate the XS. - real(8), intent(out) :: sig_t ! Total cross section - real(8), intent(out) :: sig_a ! Absorption cross section - real(8), intent(out) :: sig_f ! Fission cross section - complex(8) :: w_val ! The faddeeva function evaluated at Z - complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) - complex(8) :: sig_t_factor(multipole % num_l) - real(8) :: sqrtE ! sqrt(E), eV - real(8) :: invE ! 1/E, eV - real(8) :: dopp ! sqrt(atomic weight ratio / kT) - integer :: i_pole ! index of pole - integer :: i_window ! index of window - integer :: startw ! window start pointer (for poles) - integer :: endw ! window end pointer - real(8) :: T - - ! ========================================================================== - ! Bookkeeping - - ! Define some frequently used variables. - sqrtE = sqrt(E) - invE = ONE / E - T = sqrtkT**2 / K_BOLTZMANN - - if (sqrtkT == ZERO) call fatal_error("Windowed multipole temperature & - &derivatives are not implemented for 0 Kelvin cross sections.") - - ! Locate us - i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & - + ONE) - startw = multipole % w_start(i_window) - endw = multipole % w_end(i_window) - - ! Fill in factors. - if (startw <= endw) then - call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - end if - - ! Initialize the ouptut cross sections. - sig_t = ZERO - sig_a = ZERO - sig_f = ZERO - - ! TODO Polynomials: Some of the curvefit polynomials Doppler broaden so - ! rigorously we should be computing the derivative of those. But in - ! practice, those derivatives are only large at very low energy and they - ! have no effect on reactor calculations. - - ! ========================================================================== - ! Add the contribution from the poles in this window. - - dopp = multipole % sqrtAWR / sqrtkT - if (endw >= startw) then - do i_pole = startw, endw - Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp - w_val = -invE * SQRT_PI * HALF * w_derivative(Z, 2) - if (multipole % formalism == FORM_MLBW) then - sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & - sig_t_factor(multipole%l_value(i_pole)) + & - multipole % data(MLBW_RX, i_pole)) * w_val) - sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) - end if - else if (multipole % formalism == FORM_RM) then - sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & - sig_t_factor(multipole % l_value(i_pole))) - sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) - if (multipole % fissionable) then - sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) - end if - end if - end do - sig_t = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_t - sig_a = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_a - sig_f = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_f - end if - end subroutine multipole_deriv_eval - -!=============================================================================== -! COMPUTE_SIG_T_FACTOR calculates the sig_t_factor, a factor inside of the sig_t -! equation not present in the sig_a and sig_f equations. -!=============================================================================== - - subroutine compute_sig_t_factor(multipole, sqrtE, sig_t_factor) - type(MultipoleArray), intent(in) :: multipole - real(8), intent(in) :: sqrtE - complex(8), intent(out) :: sig_t_factor(multipole % num_l) - - integer :: iL - real(8) :: twophi(multipole % num_l) - real(8) :: arg - - do iL = 1, multipole % num_l - twophi(iL) = multipole % pseudo_k0RS(iL) * sqrtE - if (iL == 2) then - twophi(iL) = twophi(iL) - atan(twophi(iL)) - else if (iL == 3) then - arg = 3.0_8 * twophi(iL) / (3.0_8 - twophi(iL)**2) - twophi(iL) = twophi(iL) - atan(arg) - else if (iL == 4) then - arg = twophi(iL) * (15.0_8 - twophi(iL)**2) & - / (15.0_8 - 6.0_8 * twophi(iL)**2) - twophi(iL) = twophi(iL) - atan(arg) - end if - end do - - twophi = 2.0_8 * twophi - sig_t_factor = cmplx(cos(twophi), -sin(twophi), KIND=8) - end subroutine compute_sig_t_factor - -!=============================================================================== -! 0K_ELASTIC_XS determines the microscopic 0K elastic cross section -! for a given nuclide at the trial relative energy used in resonance scattering -!=============================================================================== - - pure function elastic_xs_0K(E, nuc) result(xs_out) - real(8), intent(in) :: E ! trial energy - type(Nuclide), intent(in) :: nuc ! target nuclide at temperature - real(8) :: xs_out ! 0K xs at trial energy - - integer :: i_grid ! index on nuclide energy grid - integer :: n_grid - real(8) :: f ! interp factor on nuclide energy grid - - ! Determine index on nuclide energy grid - n_grid = size(nuc % energy_0K) - if (E < nuc % energy_0K(1)) then - i_grid = 1 - elseif (E > nuc % energy_0K(n_grid)) then - i_grid = n_grid - 1 - else - i_grid = binary_search(nuc % energy_0K, n_grid, E) - end if - - ! check for rare case where two energy points are the same - if (nuc % energy_0K(i_grid) == nuc % energy_0K(i_grid+1)) then - i_grid = i_grid + 1 - end if - - ! calculate interpolation factor - f = (E - nuc % energy_0K(i_grid)) & - & / (nuc % energy_0K(i_grid + 1) - nuc % energy_0K(i_grid)) - - ! Calculate microscopic nuclide elastic cross section - xs_out = (ONE - f) * nuc % elastic_0K(i_grid) & - & + f * nuc % elastic_0K(i_grid + 1) - - end function elastic_xs_0K - -end module cross_section diff --git a/src/material_header.F90 b/src/material_header.F90 index a3ce32db3d..ae15ec5700 100644 --- a/src/material_header.F90 +++ b/src/material_header.F90 @@ -7,6 +7,7 @@ module material_header use error use nuclide_header use sab_header + use simulation_header, only: log_spacing use stl_vector, only: VectorReal, VectorInt use string, only: to_str @@ -64,6 +65,7 @@ module material_header procedure :: set_density => material_set_density procedure :: init_nuclide_index => material_init_nuclide_index procedure :: assign_sab_tables => material_assign_sab_tables + procedure :: calculate_xs => material_calculate_xs end type Material integer(C_INT32_T), public, bind(C) :: n_materials ! # of materials @@ -248,6 +250,115 @@ contains if (allocated(this % names)) deallocate(this % names) end subroutine material_assign_sab_tables +!=============================================================================== +! MATERIAL_CALCULATE_XS determines the macroscopic cross sections for the material the +! particle is currently traveling through. +!=============================================================================== + + subroutine material_calculate_xs(this, E, sqrtkT, micro_xs, nuclides, & + material_xs) + class(Material), intent(in) :: this + real(8), intent(in) :: E ! Particle energy + real(8), intent(in) :: sqrtkT ! Last temperature sampled + type(Nuclide), allocatable, intent(in) :: nuclides(:) + type(NuclideMicroXS), allocatable, intent(inout) :: micro_xs(:) ! Cache for each nuclide + type(MaterialMacroXS), intent(inout) :: material_xs ! Cache for current material + + integer :: i ! loop index over nuclides + integer :: i_nuclide ! index into nuclides array + integer :: i_sab ! index into sab_tables array + integer :: j ! index in this % i_sab_nuclides + integer :: i_grid ! index into logarithmic mapping array or material + ! union grid + real(8) :: atom_density ! atom density of a nuclide + real(8) :: sab_frac ! fraction of atoms affected by S(a,b) + logical :: check_sab ! should we check for S(a,b) table? + + ! Set all material macroscopic cross sections to zero + material_xs % total = ZERO + material_xs % absorption = ZERO + material_xs % fission = ZERO + material_xs % nu_fission = ZERO + + ! Find energy index on energy grid + i_grid = int(log(E/energy_min_neutron)/log_spacing) + + ! Determine if this material has S(a,b) tables + check_sab = (this % n_sab > 0) + + ! Initialize position in i_sab_nuclides + j = 1 + + ! Add contribution from each nuclide in material + do i = 1, this % n_nuclides + ! ====================================================================== + ! CHECK FOR S(A,B) TABLE + + i_sab = 0 + sab_frac = ZERO + + ! Check if this nuclide matches one of the S(a,b) tables specified. + ! This relies on i_sab_nuclides being in sorted order + if (check_sab) then + if (i == this % i_sab_nuclides(j)) then + ! Get index in sab_tables + i_sab = this % i_sab_tables(j) + sab_frac = this % sab_fracs(j) + + ! If particle energy is greater than the highest energy for the + ! S(a,b) table, then don't use the S(a,b) table + if (E > sab_tables(i_sab) % data(1) % threshold_inelastic) then + i_sab = 0 + end if + + ! Increment position in i_sab_nuclides + j = j + 1 + + ! Don't check for S(a,b) tables if there are no more left + if (j > size(this % i_sab_tables)) check_sab = .false. + end if + end if + + ! ====================================================================== + ! CALCULATE MICROSCOPIC CROSS SECTION + + ! Determine microscopic cross sections for this nuclide + i_nuclide = this % nuclide(i) + + ! Calculate microscopic cross section for this nuclide + if (E /= micro_xs(i_nuclide) % last_E & + .or. sqrtkT /= micro_xs(i_nuclide) % last_sqrtkT & + .or. i_sab /= micro_xs(i_nuclide) % index_sab & + .or. sab_frac /= micro_xs(i_nuclide) % sab_frac) then + call nuclides(i_nuclide) % calculate_xs(i_sab, E, i_grid, & + sqrtkT, sab_frac, i_nuclide, micro_xs(i_nuclide)) + end if + + ! ====================================================================== + ! ADD TO MACROSCOPIC CROSS SECTION + + ! Copy atom density of nuclide in material + atom_density = this % atom_density(i) + + ! Add contributions to material macroscopic total cross section + material_xs % total = material_xs % total + & + atom_density * micro_xs(i_nuclide) % total + + ! Add contributions to material macroscopic absorption cross section + material_xs % absorption = material_xs % absorption + & + atom_density * micro_xs(i_nuclide) % absorption + + ! Add contributions to material macroscopic fission cross section + material_xs % fission = material_xs % fission + & + atom_density * micro_xs(i_nuclide) % fission + + ! Add contributions to material macroscopic nu-fission cross section + material_xs % nu_fission = material_xs % nu_fission + & + atom_density * micro_xs(i_nuclide) % nu_fission + end do + + end subroutine material_calculate_xs + !=============================================================================== ! FREE_MEMORY_MATERIAL deallocates global arrays defined in this module !=============================================================================== diff --git a/src/mgxs_header.F90 b/src/mgxs_header.F90 index a99939f4c3..6eabefae3c 100644 --- a/src/mgxs_header.F90 +++ b/src/mgxs_header.F90 @@ -163,10 +163,11 @@ module mgxs_header real(8), intent(inout) :: wgt ! Particle weight end subroutine mgxs_sample_scatter_ - subroutine mgxs_calculate_xs_(this, gin, uvw, xs) + subroutine mgxs_calculate_xs_(this, gin, sqrtkT, uvw, xs) import Mgxs, MaterialMacroXS - class(Mgxs), intent(in) :: this + class(Mgxs), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data end subroutine mgxs_calculate_xs_ @@ -3481,12 +3482,16 @@ contains ! for the material the particle is currently traveling through. !=============================================================================== - subroutine mgxsiso_calculate_xs(this, gin, uvw, xs) - class(MgxsIso), intent(in) :: this + subroutine mgxsiso_calculate_xs(this, gin, sqrtkT, uvw, xs) + class(MgxsIso), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data + ! Update the temperature index + call this % find_temperature(sqrtkT) + xs % total = this % xs(this % index_temp) % total(gin) xs % absorption = this % xs(this % index_temp) % absorption(gin) xs % nu_fission = & @@ -3495,15 +3500,19 @@ contains end subroutine mgxsiso_calculate_xs - subroutine mgxsang_calculate_xs(this, gin, uvw, xs) - class(MgxsAngle), intent(in) :: this + subroutine mgxsang_calculate_xs(this, gin, sqrtkT, uvw, xs) + class(MgxsAngle), intent(inout) :: this integer, intent(in) :: gin ! Incoming neutron group + real(8), intent(in) :: sqrtkT ! Material temperature real(8), intent(in) :: uvw(3) ! Incoming neutron direction type(MaterialMacroXS), intent(inout) :: xs ! Resultant Mgxs Data integer :: iazi, ipol + ! Update the temperature and angle indices + call this % find_temperature(sqrtkT) call find_angle(this % polar, this % azimuthal, uvw, iazi, ipol) + xs % total = this % xs(this % index_temp) % & total(gin, iazi, ipol) xs % absorption = this % xs(this % index_temp) % & diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 1ca5849146..9949610255 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -3,26 +3,33 @@ module nuclide_header use, intrinsic :: ISO_FORTRAN_ENV use, intrinsic :: ISO_C_BINDING - use hdf5, only: HID_T, HSIZE_T, SIZE_T + use hdf5, only: HID_T, HSIZE_T, SIZE_T - use algorithm, only: sort, find + use algorithm, only: sort, find, binary_search use constants - use dict_header, only: DictIntInt, DictCharInt - use endf, only: reaction_name, is_fission, is_disappearance - use endf_header, only: Function1D, Polynomial, Tabulated1D + use dict_header, only: DictIntInt, DictCharInt + use endf, only: reaction_name, is_fission, is_disappearance + use endf_header, only: Function1D, Polynomial, Tabulated1D use error use hdf5_interface - use list_header, only: ListInt - use math, only: evaluate_legendre + use list_header, only: ListInt + use math, only: faddeeva, w_derivative, & + broaden_wmp_polynomials + use multipole_header, only: FORM_RM, FORM_MLBW, MP_EA, RM_RT, RM_RA, & + RM_RF, MLBW_RT, MLBW_RX, MLBW_RA, MLBW_RF, & + FIT_T, FIT_A, FIT_F, MultipoleArray use message_passing - use multipole_header, only: MultipoleArray - use product_header, only: AngleEnergyContainer - use reaction_header, only: Reaction + use multipole_header, only: MultipoleArray + use product_header, only: AngleEnergyContainer + use random_lcg, only: prn, future_prn, prn_set_stream + use reaction_header, only: Reaction + use sab_header, only: SAlphaBeta, sab_tables use secondary_uncorrelated, only: UncorrelatedAngleEnergy use settings - use stl_vector, only: VectorInt, VectorReal + use stl_vector, only: VectorInt, VectorReal use string - use urr_header, only: UrrData + use simulation_header, only: need_depletion_rx + use urr_header, only: UrrData implicit none @@ -108,6 +115,8 @@ module nuclide_header procedure :: init_grid => nuclide_init_grid procedure :: nu => nuclide_nu procedure, private :: create_derived => nuclide_create_derived + procedure :: calculate_xs => nuclide_calculate_xs + procedure :: calculate_elastic_xs => nuclide_calculate_elastic_xs end type Nuclide !=============================================================================== @@ -800,6 +809,737 @@ contains end subroutine nuclide_init_grid +!=============================================================================== +! NUCLIDE_CALCULATE_XS determines microscopic cross sections for the nuclide +! at the energy of the given particle +!=============================================================================== + + subroutine nuclide_calculate_xs(this, i_sab, E, i_log_union, sqrtkT, & + sab_frac, i_nuclide, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_sab ! index into sab_tables array + real(8), intent(in) :: E ! energy + integer, intent(in) :: i_log_union ! index into logarithmic mapping array or + ! material union energy grid + real(8), intent(in) :: sqrtkT ! square root of kT, material dependent + real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) + !!!TODO: i_nuclide is only needed to keep the URR prn stream consistent + !!! to ensure tests pass; this can be removed when this requirement can be + !!! relaxed + integer, intent(in) :: i_nuclide ! Index of this in the nuclides array + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + logical :: use_mp ! true if XS can be calculated with windowed multipole + integer :: i_temp ! index for temperature + integer :: i_grid ! index on nuclide energy grid + integer :: i_low ! lower logarithmic mapping index + integer :: i_high ! upper logarithmic mapping index + integer :: i_rxn ! reaction index + integer :: j ! index in DEPLETION_RX + real(8) :: f ! interp factor on nuclide energy grid + real(8) :: kT ! temperature in eV + real(8) :: sig_t, sig_a, sig_f ! Intermediate multipole variables + + ! Initialize cached cross sections to zero + micro_xs % elastic = CACHE_INVALID + micro_xs % thermal = ZERO + micro_xs % thermal_elastic = ZERO + + ! Check to see if there is multipole data present at this energy + use_mp = .false. + if (this % mp_present) then + if (E >= this % multipole % start_E .and. & + E <= this % multipole % end_E) then + use_mp = .true. + end if + end if + + ! Evaluate multipole or interpolate + if (use_mp) then + ! Call multipole kernel + call multipole_eval(this % multipole, E, sqrtkT, sig_t, sig_a, sig_f) + + micro_xs % total = sig_t + micro_xs % absorption = sig_a + micro_xs % fission = sig_f + + if (this % fissionable) then + micro_xs % nu_fission = sig_f * this % nu(E, EMISSION_TOTAL) + else + micro_xs % nu_fission = ZERO + end if + + if (need_depletion_rx) then + ! Initialize all reaction cross sections to zero + micro_xs % reaction(:) = ZERO + + ! Only non-zero reaction is (n,gamma) + micro_xs % reaction(4) = sig_a - sig_f + end if + + ! Ensure these values are set + ! Note, the only time either is used is in one of 4 places: + ! 1. physics.F90 - scatter - For inelastic scatter. + ! 2. physics.F90 - sample_fission - For partial fissions. + ! 3. tally.F90 - score_general - For tallying on MTxxx reactions. + ! 4. cross_section.F90 - calculate_urr_xs - For unresolved purposes. + ! It is worth noting that none of these occur in the resolved + ! resonance range, so the value here does not matter. index_temp is + ! set to -1 to force a segfault in case a developer messes up and tries + ! to use it with multipole. + micro_xs % index_temp = -1 + micro_xs % index_grid = 0 + micro_xs % interp_factor = ZERO + + else + ! Find the appropriate temperature index. + kT = sqrtkT**2 + select case (temperature_method) + case (TEMPERATURE_NEAREST) + i_temp = minloc(abs(this % kTs - kT), dim=1) + + case (TEMPERATURE_INTERPOLATION) + ! Find temperatures that bound the actual temperature + do i_temp = 1, size(this % kTs) - 1 + if (this % kTs(i_temp) <= kT .and. kT < this % kTs(i_temp + 1)) exit + end do + + ! Randomly sample between temperature i and i+1 + f = (kT - this % kTs(i_temp)) / & + (this % kTs(i_temp + 1) - this % kTs(i_temp)) + if (f > prn()) i_temp = i_temp + 1 + end select + + associate (grid => this % grid(i_temp), xs => this % xs(i_temp)) + ! Determine the energy grid index using a logarithmic mapping to + ! reduce the energy range over which a binary search needs to be + ! performed + + if (E < grid % energy(1)) then + i_grid = 1 + elseif (E > grid % energy(size(grid % energy))) then + i_grid = size(grid % energy) - 1 + else + ! Determine bounding indices based on which equal log-spaced + ! interval the energy is in + i_low = grid % grid_index(i_log_union) + i_high = grid % grid_index(i_log_union + 1) + 1 + + ! Perform binary search over reduced range + i_grid = binary_search(grid % energy(i_low:i_high), & + i_high - i_low + 1, E) + i_low - 1 + end if + + ! check for rare case where two energy points are the same + if (grid % energy(i_grid) == grid % energy(i_grid + 1)) & + i_grid = i_grid + 1 + + ! calculate interpolation factor + f = (E - grid % energy(i_grid)) / & + (grid % energy(i_grid + 1) - grid % energy(i_grid)) + + micro_xs % index_temp = i_temp + micro_xs % index_grid = i_grid + micro_xs % interp_factor = f + + ! Calculate microscopic nuclide total cross section + micro_xs % total = (ONE - f) * xs % value(XS_TOTAL,i_grid) & + + f * xs % value(XS_TOTAL,i_grid + 1) + + ! Calculate microscopic nuclide absorption cross section + micro_xs % absorption = (ONE - f) * xs % value(XS_ABSORPTION, & + i_grid) + f * xs % value(XS_ABSORPTION,i_grid + 1) + + if (this % fissionable) then + ! Calculate microscopic nuclide total cross section + micro_xs % fission = (ONE - f) * xs % value(XS_FISSION,i_grid) & + + f * xs % value(XS_FISSION,i_grid + 1) + + ! Calculate microscopic nuclide nu-fission cross section + micro_xs % nu_fission = (ONE - f) * xs % value(XS_NU_FISSION, & + i_grid) + f * xs % value(XS_NU_FISSION,i_grid + 1) + else + micro_xs % fission = ZERO + micro_xs % nu_fission = ZERO + end if + end associate + + ! Depletion-related reactions + if (need_depletion_rx) then + do j = 1, 6 + ! Initialize reaction xs to zero + micro_xs % reaction(j) = ZERO + + ! If reaction is present and energy is greater than threshold, set + ! the reaction xs appropriately + i_rxn = this % reaction_index(DEPLETION_RX(j)) + if (i_rxn > 0) then + associate (xs => this % reactions(i_rxn) % xs(i_temp)) + if (i_grid >= xs % threshold) then + micro_xs % reaction(j) = (ONE - f) * & + xs % value(i_grid - xs % threshold + 1) + & + f * xs % value(i_grid - xs % threshold + 2) + end if + end associate + end if + end do + end if + + end if + + ! Initialize sab treatment to false + micro_xs % index_sab = NONE + micro_xs % sab_frac = ZERO + + ! Initialize URR probability table treatment to false + micro_xs % use_ptable = .false. + + ! If there is S(a,b) data for this nuclide, we need to set the sab_scatter + ! and sab_elastic cross sections and correct the total and elastic cross + ! sections. + + if (i_sab > 0) then + call calculate_sab_xs(this, i_sab, E, sqrtkT, sab_frac, micro_xs) + end if + + ! If the particle is in the unresolved resonance range and there are + ! probability tables, we need to determine cross sections from the table + + if (urr_ptables_on .and. this % urr_present .and. .not. use_mp) then + if (E > this % urr_data(i_temp) % energy(1) .and. E < this % & + urr_data(i_temp) % energy(this % urr_data(i_temp) % n_energy)) then + call calculate_urr_xs(this, i_temp, E, i_nuclide, micro_xs) + end if + end if + + micro_xs % last_E = E + micro_xs % last_sqrtkT = sqrtkT + + end subroutine nuclide_calculate_xs + +!=============================================================================== +! NUCLIDE_CALCULATE_ELASTIC_XS precalculates the free atom elastic scattering +! cross section. Normally it is not needed until a collision actually occurs in +! a material. However, in the thermal and unresolved resonance regions, we have +! to calculate it early to adjust the total cross section correctly. +!=============================================================================== + + subroutine nuclide_calculate_elastic_xs(this, micro_xs) + class(Nuclide), intent(in) :: this + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_temp + integer :: i_grid + real(8) :: f + + ! Get temperature index, grid index, and interpolation factor + i_temp = micro_xs % index_temp + i_grid = micro_xs % index_grid + f = micro_xs % interp_factor + + if (i_temp > 0) then + associate (xs => this % reactions(1) % xs(i_temp) % value) + micro_xs % elastic = (ONE - f) * xs(i_grid) + f * xs(i_grid + 1) + end associate + else + ! For multipole, elastic is total - absorption + micro_xs % elastic = micro_xs % total - micro_xs % absorption + end if + end subroutine nuclide_calculate_elastic_xs + +!=============================================================================== +! CALCULATE_SAB_XS determines the elastic and inelastic scattering +! cross-sections in the thermal energy range. These cross sections replace a +! fraction of whatever data were taken from the normal Nuclide table. +!=============================================================================== + + subroutine calculate_sab_xs(this, i_sab, E, sqrtkT, sab_frac, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_sab ! index into sab_tables array + real(8), intent(in) :: E ! energy + real(8), intent(in) :: sqrtkT ! temperature + real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_temp ! temperature index + real(8) :: inelastic ! S(a,b) inelastic cross section + real(8) :: elastic ! S(a,b) elastic cross section + + ! Set flag that S(a,b) treatment should be used for scattering + micro_xs % index_sab = i_sab + + ! Calculate the S(a,b) cross section + call sab_tables(i_sab) % calculate_xs(E, sqrtkT, i_temp, elastic, inelastic) + + ! Store the S(a,b) cross sections. + micro_xs % thermal = sab_frac * (elastic + inelastic) + micro_xs % thermal_elastic = sab_frac * elastic + + ! Calculate free atom elastic cross section + call this % calculate_elastic_xs(micro_xs) + + ! Correct total and elastic cross sections + micro_xs % total = micro_xs % total + micro_xs % thermal - & + sab_frac * micro_xs % elastic + micro_xs % elastic = micro_xs % thermal + (ONE - sab_frac) * & + micro_xs % elastic + + ! Save temperature index and thermal fraction + micro_xs % index_temp_sab = i_temp + micro_xs % sab_frac = sab_frac + + end subroutine calculate_sab_xs + +!=============================================================================== +! MULTIPOLE_EVAL evaluates the windowed multipole equations for cross +! sections in the resolved resonance regions +!=============================================================================== + + subroutine multipole_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) + type(MultipoleArray), intent(in) :: multipole ! The windowed multipole + ! object to process. + real(8), intent(in) :: E ! The energy at which to + ! evaluate the cross section + real(8), intent(in) :: sqrtkT ! The temperature in the form + ! sqrt(kT), at which + ! to evaluate the XS. + real(8), intent(out) :: sig_t ! Total cross section + real(8), intent(out) :: sig_a ! Absorption cross section + real(8), intent(out) :: sig_f ! Fission cross section + complex(8) :: psi_chi ! The value of the psi-chi function for the + ! asymptotic form + complex(8) :: c_temp ! complex temporary variable + complex(8) :: w_val ! The faddeeva function evaluated at Z + complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) + complex(8) :: sig_t_factor(multipole % num_l) + real(8) :: broadened_polynomials(multipole % fit_order + 1) + real(8) :: sqrtE ! sqrt(E), eV + real(8) :: invE ! 1/E, eV + real(8) :: dopp ! sqrt(atomic weight ratio / kT) = 1 / (2 sqrt(xi)) + real(8) :: temp ! real temporary value + integer :: i_pole ! index of pole + integer :: i_poly ! index of curvefit + integer :: i_window ! index of window + integer :: startw ! window start pointer (for poles) + integer :: endw ! window end pointer + + ! ========================================================================== + ! Bookkeeping + + ! Define some frequently used variables. + sqrtE = sqrt(E) + invE = ONE / E + + ! Locate us. + i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & + + ONE) + startw = multipole % w_start(i_window) + endw = multipole % w_end(i_window) + + ! Fill in factors. + if (startw <= endw) then + call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + end if + + ! Initialize the ouptut cross sections. + sig_t = ZERO + sig_a = ZERO + sig_f = ZERO + + ! ========================================================================== + ! Add the contribution from the curvefit polynomial. + + if (sqrtkT /= ZERO .and. multipole % broaden_poly(i_window) == 1) then + ! Broaden the curvefit. + dopp = multipole % sqrtAWR / sqrtkT + call broaden_wmp_polynomials(E, dopp, multipole % fit_order + 1, & + broadened_polynomials) + do i_poly = 1, multipole % fit_order+1 + sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) & + * broadened_polynomials(i_poly) + sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) & + * broadened_polynomials(i_poly) + if (multipole % fissionable) then + sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) & + * broadened_polynomials(i_poly) + end if + end do + else ! Evaluate as if it were a polynomial + temp = invE + do i_poly = 1, multipole % fit_order+1 + sig_t = sig_t + multipole % curvefit(FIT_T, i_poly, i_window) * temp + sig_a = sig_a + multipole % curvefit(FIT_A, i_poly, i_window) * temp + if (multipole % fissionable) then + sig_f = sig_f + multipole % curvefit(FIT_F, i_poly, i_window) * temp + end if + temp = temp * sqrtE + end do + end if + + ! ========================================================================== + ! Add the contribution from the poles in this window. + + if (sqrtkT == ZERO) then + ! If at 0K, use asymptotic form. + do i_pole = startw, endw + psi_chi = -ONEI / (multipole % data(MP_EA, i_pole) - sqrtE) + c_temp = psi_chi / E + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real(multipole % data(MLBW_RT, i_pole) * c_temp * & + sig_t_factor(multipole % l_value(i_pole))) & + + real(multipole % data(MLBW_RX, i_pole) * c_temp) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * c_temp) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * c_temp) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * c_temp * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * c_temp) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * c_temp) + end if + end if + end do + else + ! At temperature, use Faddeeva function-based form. + dopp = multipole % sqrtAWR / sqrtkT + if (endw >= startw) then + do i_pole = startw, endw + Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp + w_val = faddeeva(Z) * dopp * invE * SQRT_PI + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & + sig_t_factor(multipole % l_value(i_pole)) + & + multipole % data(MLBW_RX, i_pole)) * w_val) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) + end if + end if + end do + end if + end if + end subroutine multipole_eval + +!=============================================================================== +! MULTIPOLE_DERIV_EVAL evaluates the windowed multipole equations for the +! derivative of cross sections in the resolved resonance regions with respect to +! temperature. +!=============================================================================== + + subroutine multipole_deriv_eval(multipole, E, sqrtkT, sig_t, sig_a, sig_f) + type(MultipoleArray), intent(in) :: multipole ! The windowed multipole + ! object to process. + real(8), intent(in) :: E ! The energy at which to + ! evaluate the cross section + real(8), intent(in) :: sqrtkT ! The temperature in the form + ! sqrt(kT), at which to + ! evaluate the XS. + real(8), intent(out) :: sig_t ! Total cross section + real(8), intent(out) :: sig_a ! Absorption cross section + real(8), intent(out) :: sig_f ! Fission cross section + complex(8) :: w_val ! The faddeeva function evaluated at Z + complex(8) :: Z ! sqrt(atomic weight ratio / kT) * (sqrt(E) - pole) + complex(8) :: sig_t_factor(multipole % num_l) + real(8) :: sqrtE ! sqrt(E), eV + real(8) :: invE ! 1/E, eV + real(8) :: dopp ! sqrt(atomic weight ratio / kT) + integer :: i_pole ! index of pole + integer :: i_window ! index of window + integer :: startw ! window start pointer (for poles) + integer :: endw ! window end pointer + real(8) :: T + + ! ========================================================================== + ! Bookkeeping + + ! Define some frequently used variables. + sqrtE = sqrt(E) + invE = ONE / E + T = sqrtkT**2 / K_BOLTZMANN + + if (sqrtkT == ZERO) call fatal_error("Windowed multipole temperature & + &derivatives are not implemented for 0 Kelvin cross sections.") + + ! Locate us + i_window = floor((sqrtE - sqrt(multipole % start_E)) / multipole % spacing & + + ONE) + startw = multipole % w_start(i_window) + endw = multipole % w_end(i_window) + + ! Fill in factors. + if (startw <= endw) then + call compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + end if + + ! Initialize the ouptut cross sections. + sig_t = ZERO + sig_a = ZERO + sig_f = ZERO + + ! TODO Polynomials: Some of the curvefit polynomials Doppler broaden so + ! rigorously we should be computing the derivative of those. But in + ! practice, those derivatives are only large at very low energy and they + ! have no effect on reactor calculations. + + ! ========================================================================== + ! Add the contribution from the poles in this window. + + dopp = multipole % sqrtAWR / sqrtkT + if (endw >= startw) then + do i_pole = startw, endw + Z = (sqrtE - multipole % data(MP_EA, i_pole)) * dopp + w_val = -invE * SQRT_PI * HALF * w_derivative(Z, 2) + if (multipole % formalism == FORM_MLBW) then + sig_t = sig_t + real((multipole % data(MLBW_RT, i_pole) * & + sig_t_factor(multipole%l_value(i_pole)) + & + multipole % data(MLBW_RX, i_pole)) * w_val) + sig_a = sig_a + real(multipole % data(MLBW_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(MLBW_RF, i_pole) * w_val) + end if + else if (multipole % formalism == FORM_RM) then + sig_t = sig_t + real(multipole % data(RM_RT, i_pole) * w_val * & + sig_t_factor(multipole % l_value(i_pole))) + sig_a = sig_a + real(multipole % data(RM_RA, i_pole) * w_val) + if (multipole % fissionable) then + sig_f = sig_f + real(multipole % data(RM_RF, i_pole) * w_val) + end if + end if + end do + sig_t = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_t + sig_a = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_a + sig_f = -HALF*multipole % sqrtAWR / sqrt(K_BOLTZMANN) * T**(-1.5) * sig_f + end if + end subroutine multipole_deriv_eval + +!=============================================================================== +! COMPUTE_SIG_T_FACTOR calculates the sig_t_factor, a factor inside of the sig_t +! equation not present in the sig_a and sig_f equations. +!=============================================================================== + + subroutine compute_sig_t_factor(multipole, sqrtE, sig_t_factor) + type(MultipoleArray), intent(in) :: multipole + real(8), intent(in) :: sqrtE + complex(8), intent(out) :: sig_t_factor(multipole % num_l) + + integer :: iL + real(8) :: twophi(multipole % num_l) + real(8) :: arg + + do iL = 1, multipole % num_l + twophi(iL) = multipole % pseudo_k0RS(iL) * sqrtE + if (iL == 2) then + twophi(iL) = twophi(iL) - atan(twophi(iL)) + else if (iL == 3) then + arg = 3.0_8 * twophi(iL) / (3.0_8 - twophi(iL)**2) + twophi(iL) = twophi(iL) - atan(arg) + else if (iL == 4) then + arg = twophi(iL) * (15.0_8 - twophi(iL)**2) & + / (15.0_8 - 6.0_8 * twophi(iL)**2) + twophi(iL) = twophi(iL) - atan(arg) + end if + end do + + twophi = 2.0_8 * twophi + sig_t_factor = cmplx(cos(twophi), -sin(twophi), KIND=8) + end subroutine compute_sig_t_factor + +!=============================================================================== +! 0K_ELASTIC_XS determines the microscopic 0K elastic cross section +! for a given nuclide at the trial relative energy used in resonance scattering +!=============================================================================== + + pure function elastic_xs_0K(E, nuc) result(xs_out) + real(8), intent(in) :: E ! trial energy + type(Nuclide), intent(in) :: nuc ! target nuclide at temperature + real(8) :: xs_out ! 0K xs at trial energy + + integer :: i_grid ! index on nuclide energy grid + integer :: n_grid + real(8) :: f ! interp factor on nuclide energy grid + + ! Determine index on nuclide energy grid + n_grid = size(nuc % energy_0K) + if (E < nuc % energy_0K(1)) then + i_grid = 1 + elseif (E > nuc % energy_0K(n_grid)) then + i_grid = n_grid - 1 + else + i_grid = binary_search(nuc % energy_0K, n_grid, E) + end if + + ! check for rare case where two energy points are the same + if (nuc % energy_0K(i_grid) == nuc % energy_0K(i_grid+1)) then + i_grid = i_grid + 1 + end if + + ! calculate interpolation factor + f = (E - nuc % energy_0K(i_grid)) & + & / (nuc % energy_0K(i_grid + 1) - nuc % energy_0K(i_grid)) + + ! Calculate microscopic nuclide elastic cross section + xs_out = (ONE - f) * nuc % elastic_0K(i_grid) & + & + f * nuc % elastic_0K(i_grid + 1) + + end function elastic_xs_0K + +!=============================================================================== +! CALCULATE_URR_XS determines cross sections in the unresolved resonance range +! from probability tables +!=============================================================================== + + subroutine calculate_urr_xs(this, i_temp, E, i_nuclide, micro_xs) + class(Nuclide), intent(in) :: this ! Nuclide object + integer, intent(in) :: i_temp ! temperature index + real(8), intent(in) :: E ! energy + !!!TODO: i_nuclide is only needed to keep the URR prn stream consistent + !!! to ensure tests pass; this can be removed when this requirement can be + !!! relaxed + integer, intent(in) :: i_nuclide ! Index of this in the nuclides array + type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache + + integer :: i_energy ! index for energy + integer :: i_low ! band index at lower bounding energy + integer :: i_up ! band index at upper bounding energy + real(8) :: f ! interpolation factor + real(8) :: r ! pseudo-random number + real(8) :: elastic ! elastic cross section + real(8) :: capture ! (n,gamma) cross section + real(8) :: fission ! fission cross section + real(8) :: inelastic ! inelastic cross section + + micro_xs % use_ptable = .true. + + associate (urr => this % urr_data(i_temp)) + ! determine energy table + i_energy = 1 + do + if (E < urr % energy(i_energy + 1)) exit + i_energy = i_energy + 1 + end do + + ! determine interpolation factor on table + f = (E - urr % energy(i_energy)) / & + (urr % energy(i_energy + 1) - urr % energy(i_energy)) + + ! sample probability table using the cumulative distribution + + ! Random numbers for xs calculation are sampled from a separated stream. + ! This guarantees the randomness and, at the same time, makes sure we reuse + ! random number for the same nuclide at different temperatures, therefore + ! preserving correlation of temperature in probability tables. + call prn_set_stream(STREAM_URR_PTABLE) + r = future_prn(int(i_nuclide, 8)) + call prn_set_stream(STREAM_TRACKING) + + i_low = 1 + do + if (urr % prob(i_energy, URR_CUM_PROB, i_low) > r) exit + i_low = i_low + 1 + end do + i_up = 1 + do + if (urr % prob(i_energy + 1, URR_CUM_PROB, i_up) > r) exit + i_up = i_up + 1 + end do + + ! determine elastic, fission, and capture cross sections from probability + ! table + if (urr % interp == LINEAR_LINEAR) then + elastic = (ONE - f) * urr % prob(i_energy, URR_ELASTIC, i_low) + & + f * urr % prob(i_energy + 1, URR_ELASTIC, i_up) + fission = (ONE - f) * urr % prob(i_energy, URR_FISSION, i_low) + & + f * urr % prob(i_energy + 1, URR_FISSION, i_up) + capture = (ONE - f) * urr % prob(i_energy, URR_N_GAMMA, i_low) + & + f * urr % prob(i_energy + 1, URR_N_GAMMA, i_up) + elseif (urr % interp == LOG_LOG) then + ! Get logarithmic interpolation factor + f = log(E / urr % energy(i_energy)) / & + log(urr % energy(i_energy + 1) / urr % energy(i_energy)) + + ! Calculate elastic cross section/factor + elastic = ZERO + if (urr % prob(i_energy, URR_ELASTIC, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_ELASTIC, i_up) > ZERO) then + elastic = exp((ONE - f) * log(urr % prob(i_energy, URR_ELASTIC, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_ELASTIC, & + i_up))) + end if + + ! Calculate fission cross section/factor + fission = ZERO + if (urr % prob(i_energy, URR_FISSION, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_FISSION, i_up) > ZERO) then + fission = exp((ONE - f) * log(urr % prob(i_energy, URR_FISSION, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_FISSION, & + i_up))) + end if + + ! Calculate capture cross section/factor + capture = ZERO + if (urr % prob(i_energy, URR_N_GAMMA, i_low) > ZERO .and. & + urr % prob(i_energy + 1, URR_N_GAMMA, i_up) > ZERO) then + capture = exp((ONE - f) * log(urr % prob(i_energy, URR_N_GAMMA, & + i_low)) + f * log(urr % prob(i_energy + 1, URR_N_GAMMA, & + i_up))) + end if + end if + + ! Determine treatment of inelastic scattering + inelastic = ZERO + if (urr % inelastic_flag > 0) then + ! Get index on energy grid and interpolation factor + i_energy = micro_xs % index_grid + f = micro_xs % interp_factor + + ! Determine inelastic scattering cross section + associate (xs => this % reactions(this % urr_inelastic) % xs(i_temp)) + if (i_energy >= xs % threshold) then + inelastic = (ONE - f) * xs % value(i_energy - xs % threshold + 1) + & + f * xs % value(i_energy - xs % threshold + 2) + end if + end associate + end if + + ! Multiply by smooth cross-section if needed + if (urr % multiply_smooth) then + call this % calculate_elastic_xs(micro_xs) + elastic = elastic * micro_xs % elastic + capture = capture * (micro_xs % absorption - micro_xs % fission) + fission = fission * micro_xs % fission + end if + + ! Check for negative values + if (elastic < ZERO) elastic = ZERO + if (fission < ZERO) fission = ZERO + if (capture < ZERO) capture = ZERO + + ! Set elastic, absorption, fission, and total cross sections. Note that the + ! total cross section is calculated as sum of partials rather than using the + ! table-provided value + micro_xs % elastic = elastic + micro_xs % absorption = capture + fission + micro_xs % fission = fission + micro_xs % total = elastic + inelastic + capture + fission + + ! Determine nu-fission cross section + if (this % fissionable) then + micro_xs % nu_fission = this % nu(E, EMISSION_TOTAL) * & + micro_xs % fission + end if + end associate + + end subroutine calculate_urr_xs + !=============================================================================== ! CHECK_DATA_VERSION checks for the right version of nuclear data within HDF5 ! files diff --git a/src/physics.F90 b/src/physics.F90 index fe242dbb78..98fef8b921 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -2,7 +2,6 @@ module physics use algorithm, only: binary_search use constants - use cross_section, only: elastic_xs_0K, calculate_elastic_xs use endf, only: reaction_name use error, only: fatal_error, warning, write_message use material_header, only: Material, materials @@ -340,7 +339,7 @@ contains ! Calculate elastic cross section if it wasn't precalculated if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then - call calculate_elastic_xs(i_nuclide) + call nuc % calculate_elastic_xs(micro_xs(i_nuclide)) end if prob = micro_xs(i_nuclide) % elastic - micro_xs(i_nuclide) % thermal diff --git a/src/sab_header.F90 b/src/sab_header.F90 index 6dd617790b..eca8e555a1 100644 --- a/src/sab_header.F90 +++ b/src/sab_header.F90 @@ -3,7 +3,7 @@ module sab_header use, intrinsic :: ISO_C_BINDING use, intrinsic :: ISO_FORTRAN_ENV - use algorithm, only: find, sort + use algorithm, only: find, sort, binary_search use constants use dict_header, only: DictIntInt, DictCharInt use distribution_univariate, only: Tabular @@ -12,7 +12,9 @@ module sab_header use hdf5_interface, only: read_attribute, get_shape, open_group, close_group, & open_dataset, read_dataset, close_dataset, get_datasets, object_exists, & get_name + use random_lcg, only: prn use secondary_correlated, only: CorrelatedAngleEnergy + use settings use stl_vector, only: VectorInt, VectorReal use string, only: to_str, str_to_int @@ -77,6 +79,7 @@ module sab_header type(SabData), allocatable :: data(:) contains procedure :: from_hdf5 => salphabeta_from_hdf5 + procedure :: calculate_xs => sab_calculate_xs end type SAlphaBeta ! S(a,b) tables @@ -360,6 +363,104 @@ contains call close_group(kT_group) end subroutine salphabeta_from_hdf5 +!=============================================================================== +! SAB_CALCULATE_XS determines the elastic and inelastic scattering +! cross-sections in the thermal energy range. +!=============================================================================== + + subroutine sab_calculate_xs(this, E, sqrtkT, i_temp, elastic, inelastic) + class(SAlphaBeta), intent(in) :: this ! S(a,b) object + real(8), intent(in) :: E ! energy + real(8), intent(in) :: sqrtkT ! temperature + integer, intent(out) :: i_temp ! index in the S(a,b)'s temperature + real(8), intent(out) :: elastic ! thermal elastic cross section + real(8), intent(out) :: inelastic ! thermal inelastic cross section + + integer :: i_grid ! index on S(a,b) energy grid + real(8) :: f ! interp factor on S(a,b) energy grid + real(8) :: kT + + ! Determine temperature for S(a,b) table + kT = sqrtkT**2 + if (temperature_method == TEMPERATURE_NEAREST) then + ! If using nearest temperature, do linear search on temperature + do i_temp = 1, size(this % kTs) + if (abs(this % kTs(i_temp) - kT) < & + K_BOLTZMANN*temperature_tolerance) exit + end do + else + ! Find temperatures that bound the actual temperature + do i_temp = 1, size(this % kTs) - 1 + if (this % kTs(i_temp) <= kT .and. & + kT < this % kTs(i_temp + 1)) exit + end do + + ! Randomly sample between temperature i and i+1 + f = (kT - this % kTs(i_temp)) / & + (this % kTs(i_temp + 1) - this % kTs(i_temp)) + if (f > prn()) i_temp = i_temp + 1 + end if + + + ! Get pointer to S(a,b) table + associate (sab => this % data(i_temp)) + + ! Get index and interpolation factor for inelastic grid + if (E < sab % inelastic_e_in(1)) then + i_grid = 1 + f = ZERO + else + i_grid = binary_search(sab % inelastic_e_in, sab % n_inelastic_e_in, E) + f = (E - sab%inelastic_e_in(i_grid)) / & + (sab%inelastic_e_in(i_grid+1) - sab%inelastic_e_in(i_grid)) + end if + + ! Calculate S(a,b) inelastic scattering cross section + inelastic = (ONE - f) * sab % inelastic_sigma(i_grid) + & + f * sab % inelastic_sigma(i_grid + 1) + + ! Check for elastic data + if (E < sab % threshold_elastic) then + ! Determine whether elastic scattering is given in the coherent or + ! incoherent approximation. For coherent, the cross section is + ! represented as P/E whereas for incoherent, it is simply P + + if (sab % elastic_mode == SAB_ELASTIC_EXACT) then + if (E < sab % elastic_e_in(1)) then + ! If energy is below that of the lowest Bragg peak, the elastic + ! cross section will be zero + elastic = ZERO + else + i_grid = binary_search(sab % elastic_e_in, & + sab % n_elastic_e_in, E) + elastic = sab % elastic_P(i_grid) / E + end if + else + ! Determine index on elastic energy grid + if (E < sab % elastic_e_in(1)) then + i_grid = 1 + else + i_grid = binary_search(sab % elastic_e_in, & + sab % n_elastic_e_in, E) + end if + + ! Get interpolation factor for elastic grid + f = (E - sab%elastic_e_in(i_grid))/(sab%elastic_e_in(i_grid+1) - & + sab%elastic_e_in(i_grid)) + + ! Calculate S(a,b) elastic scattering cross section + elastic = (ONE - f) * sab % elastic_P(i_grid) + & + f * sab % elastic_P(i_grid + 1) + end if + else + ! No elastic data + elastic = ZERO + end if + end associate + + end subroutine sab_calculate_xs + + !=============================================================================== ! FREE_MEMORY_SAB deallocates global arrays defined in this module !=============================================================================== diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index da0d8929c1..a9a5fd8bfc 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -4,7 +4,6 @@ module tally use algorithm, only: binary_search use constants - use cross_section, only: multipole_deriv_eval, calculate_elastic_xs use dict_header, only: EMPTY use error, only: fatal_error use geometry_header @@ -1018,7 +1017,7 @@ contains else if (i_nuclide > 0) then if (micro_xs(i_nuclide) % elastic == CACHE_INVALID) then - call calculate_elastic_xs(i_nuclide) + call nuclides(i_nuclide) % calculate_elastic_xs(micro_xs(i_nuclide)) end if score = micro_xs(i_nuclide) % elastic * atom_density * flux else @@ -1031,7 +1030,7 @@ contains ! Get index in nuclides array i_nuc = materials(p % material) % nuclide(l) if (micro_xs(i_nuc) % elastic == CACHE_INVALID) then - call calculate_elastic_xs(i_nuc) + call nuclides(i_nuc) % calculate_elastic_xs(micro_xs(i_nuc)) end if score = score + micro_xs(i_nuc) % elastic * atom_density_ * flux diff --git a/src/tracking.F90 b/src/tracking.F90 index 127da02226..40f20bbb07 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -1,11 +1,11 @@ module tracking use constants - use cross_section, only: calculate_xs use error, only: warning, write_message use geometry_header, only: cells use geometry, only: find_cell, distance_to_boundary, cross_lattice,& check_cell_overlap + use material_header, only: materials, Material use message_passing use mgxs_header use nuclide_header @@ -100,29 +100,30 @@ contains if (check_overlaps) call check_cell_overlap(p) ! Calculate microscopic and macroscopic cross sections - if (run_CE) then - ! If the material is the same as the last material and the temperature - ! hasn't changed, we don't need to lookup cross sections again. - if (p % material /= p % last_material .or. & - p % sqrtkT /= p % last_sqrtkT) call calculate_xs(p) - else - ! Since the MGXS can be angle dependent, this needs to be done - ! After every collision for the MGXS mode - if (p % material /= MATERIAL_VOID) then - ! Update the temperature index - call macro_xs(p % material) % obj % find_temperature(p % sqrtkT) - ! Get the data - call macro_xs(p % material) % obj % calculate_xs(p % g, & - p % coord(p % n_coord) % uvw, material_xs) + if (p % material /= MATERIAL_VOID) then + if (run_CE) then + if (p % material /= p % last_material .or. & + p % sqrtkT /= p % last_sqrtkT) then + ! If the material is the same as the last material and the + ! temperature hasn't changed, we don't need to lookup cross + ! sections again. + call materials(p % material) % calculate_xs(p % E, p % sqrtkT, & + micro_xs, nuclides, material_xs) + end if else - material_xs % total = ZERO - material_xs % absorption = ZERO - material_xs % nu_fission = ZERO - end if + ! Get the MG data + call macro_xs(p % material) % obj % calculate_xs(p % g, p % sqrtkT, & + p % coord(p % n_coord) % uvw, material_xs) - ! Finally, update the particle group while we have already checked for - ! if multi-group - p % last_g = p % g + ! Finally, update the particle group while we have already checked + ! for if multi-group + p % last_g = p % g + end if + else + material_xs % total = ZERO + material_xs % absorption = ZERO + material_xs % fission = ZERO + material_xs % nu_fission = ZERO end if ! Find the distance to the nearest boundary From 467f203bdb0a43a4a324346a6eff7dcb071c15f6 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Sun, 4 Feb 2018 17:27:58 -0500 Subject: [PATCH 037/212] Cleaning up --- src/input_xml.F90 | 2 +- src/material_header.F90 | 2 +- src/nuclide_header.F90 | 27 ++++++++++++--------------- 3 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 0b7790a51c..34a2fdd718 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -4191,7 +4191,7 @@ contains group_id = open_group(file_id, name) call nuclides(i_nuclide) % from_hdf5(group_id, nuc_temps(i_nuclide), & temperature_method, temperature_tolerance, temperature_range, & - master) + master, i_nuclide) call close_group(group_id) call file_close(file_id) diff --git a/src/material_header.F90 b/src/material_header.F90 index ae15ec5700..038e529bee 100644 --- a/src/material_header.F90 +++ b/src/material_header.F90 @@ -331,7 +331,7 @@ contains .or. i_sab /= micro_xs(i_nuclide) % index_sab & .or. sab_frac /= micro_xs(i_nuclide) % sab_frac) then call nuclides(i_nuclide) % calculate_xs(i_sab, E, i_grid, & - sqrtkT, sab_frac, i_nuclide, micro_xs(i_nuclide)) + sqrtkT, sab_frac, micro_xs(i_nuclide)) end if ! ====================================================================== diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 9949610255..fd2577508a 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -64,6 +64,7 @@ module nuclide_header integer :: A ! mass number integer :: metastable ! metastable state real(8) :: awr ! Atomic Weight Ratio + integer :: i_nuclide ! The nuclides index in the nuclides array real(8), allocatable :: kTs(:) ! temperature in eV (k*T) ! Fission information @@ -268,7 +269,7 @@ contains end subroutine nuclide_clear subroutine nuclide_from_hdf5(this, group_id, temperature, method, tolerance, & - minmax, master) + minmax, master, i_nuclide) class(Nuclide), intent(inout) :: this integer(HID_T), intent(in) :: group_id type(VectorReal), intent(in) :: temperature ! list of desired temperatures @@ -276,6 +277,7 @@ contains real(8), intent(in) :: tolerance real(8), intent(in) :: minmax(2) ! range of temperatures logical, intent(in) :: master ! if this is the master proc + integer, intent(in) :: i_nuclide ! Nuclide index in nuclides integer :: i integer :: i_closest @@ -569,6 +571,9 @@ contains ! Create derived cross section data call this % create_derived() + ! Finalize with the nuclide index + this % i_nuclide = i_nuclide + end subroutine nuclide_from_hdf5 subroutine nuclide_create_derived(this) @@ -815,7 +820,7 @@ contains !=============================================================================== subroutine nuclide_calculate_xs(this, i_sab, E, i_log_union, sqrtkT, & - sab_frac, i_nuclide, micro_xs) + sab_frac, micro_xs) class(Nuclide), intent(in) :: this ! Nuclide object integer, intent(in) :: i_sab ! index into sab_tables array real(8), intent(in) :: E ! energy @@ -823,10 +828,6 @@ contains ! material union energy grid real(8), intent(in) :: sqrtkT ! square root of kT, material dependent real(8), intent(in) :: sab_frac ! fraction of atoms affected by S(a,b) - !!!TODO: i_nuclide is only needed to keep the URR prn stream consistent - !!! to ensure tests pass; this can be removed when this requirement can be - !!! relaxed - integer, intent(in) :: i_nuclide ! Index of this in the nuclides array type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache logical :: use_mp ! true if XS can be calculated with windowed multipole @@ -882,7 +883,7 @@ contains ! 1. physics.F90 - scatter - For inelastic scatter. ! 2. physics.F90 - sample_fission - For partial fissions. ! 3. tally.F90 - score_general - For tallying on MTxxx reactions. - ! 4. cross_section.F90 - calculate_urr_xs - For unresolved purposes. + ! 4. nuclide_header.F90 - calculate_urr_xs - For unresolved purposes. ! It is worth noting that none of these occur in the resolved ! resonance range, so the value here does not matter. index_temp is ! set to -1 to force a segfault in case a developer messes up and tries @@ -1008,7 +1009,7 @@ contains if (urr_ptables_on .and. this % urr_present .and. .not. use_mp) then if (E > this % urr_data(i_temp) % energy(1) .and. E < this % & urr_data(i_temp) % energy(this % urr_data(i_temp) % n_energy)) then - call calculate_urr_xs(this, i_temp, E, i_nuclide, micro_xs) + call calculate_urr_xs(this, i_temp, E, micro_xs) end if end if @@ -1397,14 +1398,10 @@ contains ! from probability tables !=============================================================================== - subroutine calculate_urr_xs(this, i_temp, E, i_nuclide, micro_xs) + subroutine calculate_urr_xs(this, i_temp, E, micro_xs) class(Nuclide), intent(in) :: this ! Nuclide object integer, intent(in) :: i_temp ! temperature index real(8), intent(in) :: E ! energy - !!!TODO: i_nuclide is only needed to keep the URR prn stream consistent - !!! to ensure tests pass; this can be removed when this requirement can be - !!! relaxed - integer, intent(in) :: i_nuclide ! Index of this in the nuclides array type(NuclideMicroXS), intent(inout) :: micro_xs ! Cross section cache integer :: i_energy ! index for energy @@ -1438,7 +1435,7 @@ contains ! random number for the same nuclide at different temperatures, therefore ! preserving correlation of temperature in probability tables. call prn_set_stream(STREAM_URR_PTABLE) - r = future_prn(int(i_nuclide, 8)) + r = future_prn(int(this % i_nuclide, 8)) call prn_set_stream(STREAM_TRACKING) i_low = 1 @@ -1657,7 +1654,7 @@ contains group_id = open_group(file_id, name_) call nuclides(n) % from_hdf5(group_id, temperature, & temperature_method, temperature_tolerance, minmax, & - master) + master, n) call close_group(group_id) call file_close(file_id) From 160c533ae984987c17a5db5e8d6b64166cbda3a1 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Sun, 4 Feb 2018 19:00:39 -0500 Subject: [PATCH 038/212] fixed mis-indented line --- src/tracking.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tracking.F90 b/src/tracking.F90 index 40f20bbb07..f5839eb8e9 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -103,7 +103,7 @@ contains if (p % material /= MATERIAL_VOID) then if (run_CE) then if (p % material /= p % last_material .or. & - p % sqrtkT /= p % last_sqrtkT) then + p % sqrtkT /= p % last_sqrtkT) then ! If the material is the same as the last material and the ! temperature hasn't changed, we don't need to lookup cross ! sections again. From 894ec54ad7659194ed53cc806444e88cd164d649 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 23 Jan 2018 23:01:03 -0600 Subject: [PATCH 039/212] Add unit tests for material classes --- openmc/material.py | 6 +- tests/unit_tests/test_material.py | 128 ++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 tests/unit_tests/test_material.py diff --git a/openmc/material.py b/openmc/material.py index e22fe0b8ba..a59fdaa285 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -15,7 +15,7 @@ from .mixin import IDManagerMixin # Units for density supported by OpenMC -DENSITY_UNITS = ['g/cm3', 'g/cc', 'kg/cm3', 'atom/b-cm', 'atom/cm3', 'sum', +DENSITY_UNITS = ['g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3', 'sum', 'macro'] @@ -49,7 +49,7 @@ class Material(IDManagerMixin): density : float Density of the material (units defined separately) density_units : str - Units used for `density`. Can be one of 'g/cm3', 'g/cc', 'kg/cm3', + Units used for `density`. Can be one of 'g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3', 'sum', or 'macro'. The 'macro' unit only applies in the case of a multi-group calculation. depletable : bool @@ -312,7 +312,7 @@ class Material(IDManagerMixin): Parameters ---------- - units : {'g/cm3', 'g/cc', 'kg/cm3', 'atom/b-cm', 'atom/cm3', 'sum', 'macro'} + units : {'g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3', 'sum', 'macro'} Physical units of density. density : float, optional Value of the density. Must be specified unless units is given as diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py new file mode 100644 index 0000000000..46241e83df --- /dev/null +++ b/tests/unit_tests/test_material.py @@ -0,0 +1,128 @@ +import openmc +import pytest + + +@pytest.fixture(scope='module') +def uo2(): + m = openmc.Material(material_id=100, name='UO2') + m.add_nuclide('U235', 1.0) + m.add_nuclide('O16', 2.0) + m.set_density('g/cm3', 10.0) + m.depletable = True + return m + + +def test_attributes(uo2): + assert uo2.name == 'UO2' + assert uo2.id == 100 + assert uo2.depletable + + +def test_nuclides(uo2): + """Test adding/removing nuclides.""" + m = openmc.Material() + m.add_nuclide('U235', 1.0) + with pytest.raises(ValueError): + m.add_nuclide('H1', '1.0') + with pytest.raises(ValueError): + m.add_nuclide(1.0, 'H1') + with pytest.raises(ValueError): + m.add_nuclide('H1', 1.0, 'oa') + m.remove_nuclide('U235') + + +def test_elements(): + """Test adding elements.""" + m = openmc.Material() + m.add_element('Zr', 1.0) + m.add_element('U', 1.0, enrichment=4.5) + with pytest.raises(ValueError): + m.add_element('U', 1.0, enrichment=100.0) + with pytest.raises(ValueError): + m.add_element('Pu', 1.0, enrichment=3.0) + + +def test_density(): + m = openmc.Material() + for unit in ['g/cm3', 'g/cc', 'kg/m3', 'atom/b-cm', 'atom/cm3']: + m.set_density(unit, 1.0) + with pytest.raises(ValueError): + m.set_density('g/litre', 1.0) + + +def test_salphabeta(): + m = openmc.Material() + m.add_s_alpha_beta('c_H_in_H2O', 0.5) + + +def test_repr(): + m = openmc.Material() + m.add_nuclide('Zr90', 1.0) + m.add_nuclide('H2', 0.5) + m.add_s_alpha_beta('c_D_in_D2O') + m.set_density('sum') + m.temperature = 600.0 + repr(m) + + +def test_macroscopic(): + m = openmc.Material(name='UO2') + m.add_macroscopic('UO2') + with pytest.raises(ValueError): + m.add_nuclide('H1', 1.0) + with pytest.raises(ValueError): + m.add_element('O', 1.0) + with pytest.raises(ValueError): + m.add_macroscopic('Other') + + m2 = openmc.Material() + m2.add_nuclide('He4', 1.0) + with pytest.raises(ValueError): + m2.add_macroscopic('UO2') + + m.remove_macroscopic('UO2') + + +def test_isotropic(): + m = openmc.Material() + m.add_nuclide('U235', 1.0) + m.add_nuclide('O16', 2.0) + m.make_isotropic_in_lab() + assert m.isotropic == ['U235', 'O16'] + m.isotropic = ['O16'] + assert m.isotropic == ['O16'] + + +def test_get_nuclide_densities(uo2): + nucs = uo2.get_nuclide_densities() + for nuc, density, density_type in nucs.values(): + assert nuc in ('U235', 'O16') + assert density > 0 + assert density_type in ('ao', 'wo') + + +def test_get_nuclide_atom_densities(uo2): + nucs = uo2.get_nuclide_atom_densities() + for nuc, density in nucs.values(): + assert nuc in ('U235', 'O16') + assert density > 0 + + +def test_materials(tmpdir): + m1 = openmc.Material() + m1.add_nuclide('U235', 1.0, 'wo') + m1.add_nuclide('O16', 2.0, 'wo') + m1.set_density('g/cm3', 10.0) + m1.depletable = True + m1.temperature = 900.0 + + m2 = openmc.Material() + m2.add_nuclide('H1', 2.0) + m2.add_nuclide('O16', 1.0) + m2.add_s_alpha_beta('c_H_in_H2O') + m2.set_density('kg/m3', 1000.0) + + mats = openmc.Materials([m1, m2]) + mats.cross_sections = '/some/fake/cross_sections.xml' + mats.multipole_library = '/some/awesome/mp_lib/' + mats.export_to_xml(str(tmpdir.join('materials.xml'))) From b81cbc29fb054353742c564c4d5d3b69b07d4b0e Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 24 Jan 2018 13:41:41 -0600 Subject: [PATCH 040/212] Add test for Material.add_volume_information --- src/volume_calc.F90 | 2 +- tests/unit_tests/test_material.py | 48 +++++++++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/volume_calc.F90 b/src/volume_calc.F90 index 07dc5b4184..15c0497699 100644 --- a/src/volume_calc.F90 +++ b/src/volume_calc.F90 @@ -194,7 +194,7 @@ contains if (this % domain_type == FILTER_MATERIAL) then i_material = p % material do i_domain = 1, size(this % domain_id) - if (i_material == materials(i_domain) % id) then + if (materials(i_material) % id == this % domain_id(i_domain)) then call check_hit(i_domain, i_material, indices, hits, n_mat) end if end do diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 46241e83df..2da3c797f9 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -1,4 +1,6 @@ import openmc +import openmc.model +import openmc.stats import pytest @@ -12,6 +14,40 @@ def uo2(): return m +@pytest.fixture(scope='module') +def sphere_model(): + model = openmc.model.Model() + + m = openmc.Material() + m.add_nuclide('U235', 1.0) + m.set_density('g/cm3', 1.0) + model.materials.append(m) + + sph = openmc.Sphere(boundary_type='vacuum') + c = openmc.Cell(fill=m, region=-sph) + model.geometry.root_universe = openmc.Universe(cells=[c]) + + model.settings.particles = 100 + model.settings.batches = 10 + model.settings.run_mode = 'fixed source' + model.settings.source = openmc.Source(space=openmc.stats.Point()) + ll, ur = c.region.bounding_box + model.settings.volume_calculations = [ + openmc.VolumeCalculation(domains=[m], samples=1000, + lower_left=ll, upper_right=ur) + ] + return model + + +@pytest.fixture +def run_in_tmpdir(tmpdir): + orig = tmpdir.chdir() + try: + yield + finally: + orig.chdir() + + def test_attributes(uo2): assert uo2.name == 'UO2' assert uo2.id == 100 @@ -93,6 +129,14 @@ def test_isotropic(): assert m.isotropic == ['O16'] +def test_volume(run_in_tmpdir, sphere_model): + """Test adding volume information from a volume calculation.""" + sphere_model.export_to_xml() + openmc.calculate_volumes() + volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') + sphere_model.materials[0].add_volume_information(volume_calc) + + def test_get_nuclide_densities(uo2): nucs = uo2.get_nuclide_densities() for nuc, density, density_type in nucs.values(): @@ -108,7 +152,7 @@ def test_get_nuclide_atom_densities(uo2): assert density > 0 -def test_materials(tmpdir): +def test_materials(run_in_tmpdir): m1 = openmc.Material() m1.add_nuclide('U235', 1.0, 'wo') m1.add_nuclide('O16', 2.0, 'wo') @@ -125,4 +169,4 @@ def test_materials(tmpdir): mats = openmc.Materials([m1, m2]) mats.cross_sections = '/some/fake/cross_sections.xml' mats.multipole_library = '/some/awesome/mp_lib/' - mats.export_to_xml(str(tmpdir.join('materials.xml'))) + mats.export_to_xml() From 1432742fbfb37a2a1d1682aa795d8090672263c6 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 24 Jan 2018 14:29:31 -0600 Subject: [PATCH 041/212] More tests for material --- tests/unit_tests/test_material.py | 37 ++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 2da3c797f9..84627ba8c4 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -1,6 +1,7 @@ import openmc import openmc.model import openmc.stats +import openmc.examples import pytest @@ -101,7 +102,7 @@ def test_repr(): repr(m) -def test_macroscopic(): +def test_macroscopic(run_in_tmpdir): m = openmc.Material(name='UO2') m.add_macroscopic('UO2') with pytest.raises(ValueError): @@ -116,17 +117,37 @@ def test_macroscopic(): with pytest.raises(ValueError): m2.add_macroscopic('UO2') + # Make sure we can remove/add macroscopic m.remove_macroscopic('UO2') + m.add_macroscopic('UO2') + repr(m) + + # Make sure we can export a material with macroscopic data + mats = openmc.Materials([m]) + mats.export_to_xml() + + +def test_paths(): + model = openmc.examples.pwr_assembly() + model.geometry.determine_paths() + fuel = model.materials[0] + assert fuel.num_instances == 264 + assert len(fuel.paths) == 264 def test_isotropic(): - m = openmc.Material() - m.add_nuclide('U235', 1.0) - m.add_nuclide('O16', 2.0) - m.make_isotropic_in_lab() - assert m.isotropic == ['U235', 'O16'] - m.isotropic = ['O16'] - assert m.isotropic == ['O16'] + m1 = openmc.Material() + m1.add_nuclide('U235', 1.0) + m1.add_nuclide('O16', 2.0) + m1.isotropic = ['O16'] + assert m1.isotropic == ['O16'] + + m2 = openmc.Material() + m2.add_nuclide('H1', 1.0) + mats = openmc.Materials([m1, m2]) + mats.make_isotropic_in_lab() + assert m1.isotropic == ['U235', 'O16'] + assert m2.isotropic == ['H1'] def test_volume(run_in_tmpdir, sphere_model): From b0d35268f3ed656498bb40707243d115fe2bf5ea Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 25 Jan 2018 14:04:01 -0600 Subject: [PATCH 042/212] Add unit tests for surfaces --- openmc/surface.py | 2 +- tests/unit_tests/test_surface.py | 258 +++++++++++++++++++++++++++++++ 2 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 tests/unit_tests/test_surface.py diff --git a/openmc/surface.py b/openmc/surface.py index 6c29ed458c..eb44a4fe8d 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -1376,7 +1376,7 @@ class Cone(Surface): @property def r2(self): - return self.coefficients['r2'] + return self.coefficients['R2'] @x0.setter def x0(self, x0): diff --git a/tests/unit_tests/test_surface.py b/tests/unit_tests/test_surface.py new file mode 100644 index 0000000000..ded6cf1f2a --- /dev/null +++ b/tests/unit_tests/test_surface.py @@ -0,0 +1,258 @@ +import numpy as np +import openmc +import pytest + + +def assert_infinite_bb(s): + ll, ur = (-s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + + +def test_plane(): + s = openmc.Plane(A=1, B=2, C=-1, D=3, name='my plane') + assert s.a == 1 + assert s.b == 2 + assert s.c == -1 + assert s.d == 3 + assert s.boundary_type == 'transmission' + assert s.name == 'my plane' + assert s.type == 'plane' + + # Generic planes don't have well-defined bounding boxes + assert_infinite_bb(s) + + # evaluate method + x, y, z = (4, 3, 6) + assert s.evaluate((x, y, z)) == pytest.approx(s.a*x + s.b*y + s.c*z - s.d) + + # Make sure repr works + repr(s) + + +def test_xplane(): + s = openmc.XPlane(x0=3., boundary_type='reflective') + assert s.x0 == 3. + assert s.boundary_type == 'reflective' + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((3., -np.inf, -np.inf)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ur == pytest.approx((3., np.inf, np.inf)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (5, 0, 0) in +s + assert (5, 0, 0) not in -s + assert (-2, 1, 10) in -s + assert (-2, 1, 10) not in +s + + # evaluate method + assert s.evaluate((5., 0., 0.)) == pytest.approx(2.) + + # Make sure repr works + repr(s) + + +def test_yplane(): + s = openmc.YPlane(y0=3.) + assert s.y0 == 3. + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((-np.inf, 3., -np.inf)) + assert np.all(np.isinf(ur)) + ll, ur = s.bounding_box('-') + assert ur == pytest.approx((np.inf, 3., np.inf)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (0, 5, 0) in +s + assert (0, 5, 0) not in -s + assert (-2, 1, 10) in -s + assert (-2, 1, 10) not in +s + + # evaluate method + assert s.evaluate((0., 0., 0.)) == pytest.approx(-3.) + +def test_zplane(): + s = openmc.ZPlane(z0=3.) + assert s.z0 == 3. + + # Check bounding box + ll, ur = (+s).bounding_box + assert ll == pytest.approx((-np.inf, -np.inf, 3.)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ur == pytest.approx((np.inf, np.inf, 3.)) + assert np.all(np.isinf(ll)) + + # __contains__ on associated half-spaces + assert (0, 0, 5) in +s + assert (0, 0, 5) not in -s + assert (-2, 1, -10) in -s + assert (-2, 1, -10) not in +s + + # evaluate method + assert s.evaluate((0., 0., 10.)) == pytest.approx(7.) + + # Make sure repr works + repr(s) + + +def test_xcylinder(): + y, z, r = 3, 5, 2 + s = openmc.XCylinder(y0=y, z0=z, R=r) + assert s.y0 == y + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((-np.inf, y-r, z-r)) + assert ur == pytest.approx((np.inf, y+r, z+r)) + + # evaluate method + assert s.evaluate((0, y, z)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def test_periodic(): + x = openmc.XPlane(boundary_type='periodic') + y = openmc.YPlane(boundary_type='periodic') + x.periodic_surface = y + assert y.periodic_surface == x + with pytest.raises(TypeError): + x.periodic_surface = openmc.Sphere() + + +def test_ycylinder(): + x, z, r = 3, 5, 2 + s = openmc.YCylinder(x0=x, z0=z, R=r) + assert s.x0 == x + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, -np.inf, z-r)) + assert ur == pytest.approx((x+r, np.inf, z+r)) + + # evaluate method + assert s.evaluate((x, 0, z)) == pytest.approx(-r**2) + + +def test_zcylinder(): + x, y, r = 3, 5, 2 + s = openmc.ZCylinder(x0=x, y0=y, R=r) + assert s.x0 == x + assert s.y0 == y + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, y-r, -np.inf)) + assert ur == pytest.approx((x+r, y+r, np.inf)) + + # evaluate method + assert s.evaluate((x, y, 0)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def test_sphere(): + x, y, z, r = -3, 5, 6, 2 + s = openmc.Sphere(x0=x, y0=y, z0=z, R=r) + assert s.x0 == x + assert s.y0 == y + assert s.z0 == z + assert s.r == r + + # Check bounding box + ll, ur = (+s).bounding_box + assert np.all(np.isinf(ll)) + assert np.all(np.isinf(ur)) + ll, ur = (-s).bounding_box + assert ll == pytest.approx((x-r, y-r, z-r)) + assert ur == pytest.approx((x+r, y+r, z+r)) + + # evaluate method + assert s.evaluate((x, y, z)) == pytest.approx(-r**2) + + # Make sure repr works + repr(s) + + +def cone_common(apex, r2, cls): + x, y, z = apex + s = cls(x0=x, y0=y, z0=z, R2=r2) + assert s.x0 == x + assert s.y0 == y + assert s.z0 == z + assert s.r2 == r2 + + # Check bounding box + assert_infinite_bb(s) + + # evaluate method -- should be zero at apex + assert s.evaluate((x, y, z)) == pytest.approx(0.0) + + # Make sure repr works + repr(s) + + +def test_xcone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.XCone) + + +def test_ycone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.YCone) + + +def test_zcone(): + apex = (10, 0, 0) + r2 = 4 + cone_common(apex, r2, openmc.ZCone) + + +def test_quadric(): + # Make a sphere from a quadric + r = 10.0 + coeffs = {'a': 1, 'b': 1, 'c': 1, 'k': -r**2} + s = openmc.Quadric(**coeffs) + assert s.a == coeffs['a'] + assert s.b == coeffs['b'] + assert s.c == coeffs['c'] + assert s.k == coeffs['k'] + + # All other coeffs should be zero + for coeff in ('d', 'e', 'f', 'g', 'h', 'j'): + assert getattr(s, coeff) == 0.0 + + # Check bounding box + assert_infinite_bb(s) + + # evaluate method + assert s.evaluate((0., 0., 0.)) == pytest.approx(coeffs['k']) + assert s.evaluate((1., 1., 1.)) == pytest.approx(3 + coeffs['k']) From d26165f524d7f2eaed7b4dcb3c0757f78a29bf26 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 25 Jan 2018 16:26:40 -0600 Subject: [PATCH 043/212] Add tests for regions --- openmc/region.py | 8 +- tests/unit_tests/test_region.py | 134 +++++++++++++++++++++++++++++++ tests/unit_tests/test_surface.py | 1 + 3 files changed, 138 insertions(+), 5 deletions(-) create mode 100644 tests/unit_tests/test_region.py diff --git a/openmc/region.py b/openmc/region.py index eeafd28326..54797f5688 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -39,10 +39,8 @@ class Region(object): def __eq__(self, other): if not isinstance(other, type(self)): return False - elif str(self) != str(other): - return False else: - return True + return str(self) == str(other) def __ne__(self, other): return not self == other @@ -463,7 +461,7 @@ class Union(Region, MutableSequence): if memo is None: memo = {} - clone = copy.deepcopy(self) + clone = deepcopy(self) clone[:] = [n.clone(memo) for n in self] return clone @@ -584,6 +582,6 @@ class Complement(Region): if memo is None: memo = {} - clone = copy.deepcopy(self) + clone = deepcopy(self) clone.node = self.node.clone(memo) return clone diff --git a/tests/unit_tests/test_region.py b/tests/unit_tests/test_region.py new file mode 100644 index 0000000000..346ec7d95e --- /dev/null +++ b/tests/unit_tests/test_region.py @@ -0,0 +1,134 @@ +import numpy as np +import pytest +import openmc + + +@pytest.fixture +def reset(): + openmc.reset_auto_ids() + + +def assert_unbounded(region): + ll, ur = region.bounding_box + assert ll == pytest.approx((-np.inf, -np.inf, -np.inf)) + assert ur == pytest.approx((np.inf, np.inf, np.inf)) + + +def test_union(reset): + s1 = openmc.XPlane(surface_id=1, x0=5) + s2 = openmc.XPlane(surface_id=2, x0=-5) + region = +s1 | -s2 + assert isinstance(region, openmc.Union) + + # Check bounding box + assert_unbounded(region) + + # __contains__ + assert (6, 0, 0) in region + assert (-6, 0, 0) in region + assert (0, 0, 0) not in region + + # string representation + assert str(region) == '(1 | -2)' + + # Combining region with intersection + s3 = openmc.YPlane(surface_id=3) + reg2 = region & +s3 + assert (6, 1, 0) in reg2 + assert (6, -1, 0) not in reg2 + assert str(reg2) == '((1 | -2) 3)' + + +def test_intersection(reset): + s1 = openmc.XPlane(surface_id=1, x0=5) + s2 = openmc.XPlane(surface_id=2, x0=-5) + region = -s1 & +s2 + assert isinstance(region, openmc.Intersection) + + # Check bounding box + ll, ur = region.bounding_box + assert ll == pytest.approx((-5, -np.inf, -np.inf)) + assert ur == pytest.approx((5, np.inf, np.inf)) + + # __contains__ + assert (6, 0, 0) not in region + assert (-6, 0, 0) not in region + assert (0, 0, 0) in region + + # string representation + assert str(region) == '(-1 2)' + + # Combining region with union + s3 = openmc.YPlane(surface_id=3) + reg2 = region | +s3 + assert (-6, 2, 0) in reg2 + assert (-6, -2, 0) not in reg2 + assert str(reg2) == '((-1 2) | 3)' + + +def test_complement(reset): + zcyl = openmc.ZCylinder(surface_id=1, R=1.) + z0 = openmc.ZPlane(surface_id=2, z0=-5.) + z1 = openmc.ZPlane(surface_id=3, z0=5.) + outside = +zcyl | -z0 | +z1 + inside = ~outside + outside_equiv = ~(-zcyl & +z0 & -z1) + inside_equiv = ~outside_equiv + + # Check bounding box + for region in (inside, inside_equiv): + ll, ur = region.bounding_box + assert ll == pytest.approx((-1., -1., -5.)) + assert ur == pytest.approx((1., 1., 5.)) + assert_unbounded(outside) + assert_unbounded(outside_equiv) + + # string represention + assert str(inside) == '~(1 | -2 | 3)' + + # evaluate method + assert (0, 0, 0) in inside + assert (0, 0, 0) not in outside + assert (0, 0, 6) not in inside + assert (0, 0, 6) in outside + + +def test_get_surfaces(): + s1 = openmc.XPlane() + s2 = openmc.YPlane() + s3 = openmc.ZPlane() + region = (+s1 & -s2) | +s3 + + # Make sure get_surfaces() returns all surfaces + surfs = set(region.get_surfaces().values()) + assert not (surfs ^ {s1, s2, s3}) + + inverse = ~region + surfs = set(inverse.get_surfaces().values()) + assert not (surfs ^ {s1, s2, s3}) + + +def test_extend_clone(): + s1 = openmc.XPlane() + s2 = openmc.YPlane() + s3 = openmc.ZPlane() + s4 = openmc.ZCylinder() + + # extend intersection + r1 = +s1 & -s2 + r1 &= +s3 & -s4 + assert r1[:] == [+s1, -s2, +s3, -s4] + + # extend union + r2 = +s1 | -s2 + r2 |= +s3 | -s4 + assert r2[:] == [+s1, -s2, +s3, -s4] + + # clone methods + r3 = r1.clone() + assert len(r3) == len(r1) + r4 = r2.clone() + assert len(r4) == len(r2) + + r5 = ~r1 + r6 = r5.clone() diff --git a/tests/unit_tests/test_surface.py b/tests/unit_tests/test_surface.py index ded6cf1f2a..3db84cc053 100644 --- a/tests/unit_tests/test_surface.py +++ b/tests/unit_tests/test_surface.py @@ -80,6 +80,7 @@ def test_yplane(): # evaluate method assert s.evaluate((0., 0., 0.)) == pytest.approx(-3.) + def test_zplane(): s = openmc.ZPlane(z0=3.) assert s.z0 == 3. From 4180d632a466c788d39594918f237c476a51ebbc Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 26 Jan 2018 08:27:28 -0600 Subject: [PATCH 044/212] Add tests for univariate probability distributions --- openmc/stats/univariate.py | 19 ++++--- tests/unit_tests/test_stats.py | 90 ++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 10 deletions(-) create mode 100644 tests/unit_tests/test_stats.py diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index c0476ce45c..38683e6927 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -194,12 +194,12 @@ class Maxwell(Univariate): Parameters ---------- theta : float - Effective temperature for distribution + Effective temperature for distribution in eV Attributes ---------- theta : float - Effective temperature for distribution + Effective temperature for distribution in eV """ @@ -250,16 +250,16 @@ class Watt(Univariate): Parameters ---------- a : float - First parameter of distribution + First parameter of distribution in units of eV b : float - Second parameter of distribution + Second parameter of distribution in units of 1/eV Attributes ---------- a : float - First parameter of distribution + First parameter of distribution in units of eV b : float - Second parameter of distribution + Second parameter of distribution in units of 1/eV """ @@ -444,10 +444,9 @@ class Legendre(Univariate): def coefficients(self, coefficients): cv.check_type('Legendre expansion coefficients', coefficients, Iterable, Real) - for l in range(len(coefficients)): - coefficients[l] *= (2.*l + 1.)/2. - self._legendre_polynomial = np.polynomial.legendre.Legendre( - coefficients) + l = np.arange(len(coefficients)) + coeffs = (2.*l + 1.)/2. * np.array(coefficients) + self._legendre_polynomial = np.polynomial.Legendre(coeffs) def to_xml_element(self, element_name): raise NotImplementedError diff --git a/tests/unit_tests/test_stats.py b/tests/unit_tests/test_stats.py new file mode 100644 index 0000000000..cef001526c --- /dev/null +++ b/tests/unit_tests/test_stats.py @@ -0,0 +1,90 @@ +import numpy as np +import pytest +import openmc +import openmc.stats + + +def test_discrete(): + x = [0.0, 1.0, 10.0] + p = [0.3, 0.2, 0.5] + d = openmc.stats.Discrete(x, p) + assert d.x == x + assert d.p == p + assert len(d) == len(x) + d.to_xml_element('distribution') + + # Single point + d2 = openmc.stats.Discrete(1e6, 1.0) + assert d2.x == [1e6] + assert d2.p == [1.0] + assert len(d2) == 1 + + +def test_uniform(): + a, b = 10, 20 + d = openmc.stats.Uniform(a, b) + assert d.a == a + assert d.b == b + assert len(d) == 2 + + t = d.to_tabular() + assert t.x == [a, b] + assert t.p == [1/(b-a), 1/(b-a)] + assert t.interpolation == 'histogram' + + d.to_xml_element('distribution') + + +def test_maxwell(): + theta = 1.2895e6 + d = openmc.stats.Maxwell(theta) + assert d.theta == theta + assert len(d) == 1 + d.to_xml_element('distribution') + + +def test_watt(): + a, b = 0.965e6, 2.29e-6 + d = openmc.stats.Watt(a, b) + assert d.a == a + assert d.b == b + assert len(d) == 2 + d.to_xml_element('distribution') + + +def test_tabular(): + x = [0.0, 5.0, 7.0] + p = [0.1, 0.2, 0.05] + d = openmc.stats.Tabular(x, p, 'linear-linear') + assert d.x == x + assert d.p == p + assert d.interpolation == 'linear-linear' + assert len(d) == len(x) + d.to_xml_element('distribution') + + +def test_legendre(): + # Pu239 elastic scattering at 100 keV + coeffs = [1.000e+0, 1.536e-1, 1.772e-2, 5.945e-4, 3.497e-5, 1.881e-5] + d = openmc.stats.Legendre(coeffs) + assert d.coefficients == pytest.approx(coeffs) + assert len(d) == len(coeffs) + + # Integrating distribution should yield one + mu = np.linspace(-1., 1., 1000) + assert np.trapz(d(mu), mu) == pytest.approx(1.0, rel=1e-4) + + with pytest.raises(NotImplementedError): + d.to_xml_element('distribution') + +def test_mixture(): + d1 = openmc.stats.Uniform(0, 5) + d2 = openmc.stats.Uniform(3, 7) + p = [0.5, 0.5] + mix = openmc.stats.Mixture(p, [d1, d2]) + assert mix.probability == p + assert mix.distribution == [d1, d2] + assert len(mix) == 4 + + with pytest.raises(NotImplementedError): + mix.to_xml_element('distribution') From 058402954f5fedc455723c13b44c326009f5bb95 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 26 Jan 2018 10:50:29 -0600 Subject: [PATCH 045/212] Add tests for multivariate distributions in openmc.stats --- tests/unit_tests/test_stats.py | 89 ++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/tests/unit_tests/test_stats.py b/tests/unit_tests/test_stats.py index cef001526c..3a91ecd8fd 100644 --- a/tests/unit_tests/test_stats.py +++ b/tests/unit_tests/test_stats.py @@ -1,3 +1,5 @@ +from math import pi + import numpy as np import pytest import openmc @@ -77,6 +79,7 @@ def test_legendre(): with pytest.raises(NotImplementedError): d.to_xml_element('distribution') + def test_mixture(): d1 = openmc.stats.Uniform(0, 5) d2 = openmc.stats.Uniform(3, 7) @@ -88,3 +91,89 @@ def test_mixture(): with pytest.raises(NotImplementedError): mix.to_xml_element('distribution') + + +def test_polar_azimuthal(): + # default polar-azimuthal should be uniform in mu and phi + d = openmc.stats.PolarAzimuthal() + assert isinstance(d.mu, openmc.stats.Uniform) + assert d.mu.a == -1. + assert d.mu.b == 1. + assert isinstance(d.phi, openmc.stats.Uniform) + assert d.phi.a == 0. + assert d.phi.b == 2*pi + + mu = openmc.stats.Discrete(1., 1.) + phi = openmc.stats.Discrete(0., 1.) + d = openmc.stats.PolarAzimuthal(mu, phi) + assert d.mu == mu + assert d.phi == phi + + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'mu-phi' + assert elem.find('mu') is not None + assert elem.find('phi') is not None + + +def test_isotropic(): + d = openmc.stats.Isotropic() + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'isotropic' + + +def test_monodirectional(): + d = openmc.stats.Monodirectional((1., 0., 0.)) + assert d.reference_uvw == pytest.approx((1., 0., 0.)) + + elem = d.to_xml_element() + assert elem.tag == 'angle' + assert elem.attrib['type'] == 'monodirectional' + + +def test_cartesian(): + x = openmc.stats.Uniform(-10., 10.) + y = openmc.stats.Uniform(-10., 10.) + z = openmc.stats.Uniform(0., 20.) + d = openmc.stats.CartesianIndependent(x, y, z) + assert d.x == x + assert d.y == y + assert d.z == z + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'cartesian' + assert elem.find('x') is not None + assert elem.find('y') is not None + + +def test_box(): + lower_left = (-10., -10., -10.) + upper_right = (10., 10., 10.) + d = openmc.stats.Box(lower_left, upper_right) + assert d.lower_left == pytest.approx(lower_left) + assert d.upper_right == pytest.approx(upper_right) + assert not d.only_fissionable + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'box' + assert elem.find('parameters') is not None + + # only fissionable parameter + d2 = openmc.stats.Box(lower_left, upper_right, True) + assert d2.only_fissionable + elem = d2.to_xml_element() + assert elem.attrib['type'] == 'fission' + + +def test_point(): + p = (-4., 2., 10.) + d = openmc.stats.Point(p) + assert d.xyz == pytest.approx(p) + + elem = d.to_xml_element() + assert elem.tag == 'space' + assert elem.attrib['type'] == 'point' + assert elem.find('parameters') is not None From 39cd77a756c6122fae93e5fd2af820d4fd9bb8ef Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 26 Jan 2018 16:01:20 -0600 Subject: [PATCH 046/212] Have Travis install OpenMC during install step and have script call ctest --- .travis.yml | 11 +- tests/run_tests.py | 552 ------------------------------------- tools/ci/travis-install.py | 65 +++++ tools/ci/travis-install.sh | 3 + tools/ci/travis-script.sh | 13 +- 5 files changed, 83 insertions(+), 561 deletions(-) delete mode 100755 tests/run_tests.py create mode 100644 tools/ci/travis-install.py diff --git a/.travis.yml b/.travis.yml index de8b7dcc73..14e2484110 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,18 +18,17 @@ env: global: - FC=gfortran - MPI_DIR=/usr - - PHDF5_DIR=/usr - - HDF5_DIR=/usr + - HDF5_ROOT=/usr - OMP_NUM_THREADS=2 - OPENMC_CROSS_SECTIONS=$HOME/nndc_hdf5/cross_sections.xml - OPENMC_ENDF_DATA=$HOME/endf-b-vii.1 - OPENMC_MULTIPOLE_LIBRARY=$HOME/multipole_lib - PATH=$PATH:$HOME/NJOY2016/build matrix: - - OPENMC_CONFIG="^hdf5-debug$" - - OPENMC_CONFIG="^omp-hdf5-debug$" - - OPENMC_CONFIG="^mpi-hdf5-debug$" - - OPENMC_CONFIG="^phdf5-debug$" + - OMP=n MPI=n PHDF5=n + - OMP=y MPI=n PHDF5=n + - OMP=n MPI=y PHDF5=n + - OMP=n MPI=y PHDF5=y before_install: - sudo add-apt-repository ppa:nschloe/hdf5-backports -y diff --git a/tests/run_tests.py b/tests/run_tests.py deleted file mode 100755 index 6e6b886a50..0000000000 --- a/tests/run_tests.py +++ /dev/null @@ -1,552 +0,0 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os -import sys -import shutil -import re -import glob -import socket -from subprocess import call, check_output -from collections import OrderedDict -from argparse import ArgumentParser - -# Command line parsing -parser = ArgumentParser() -parser.add_argument('-j', '--parallel', dest='n_procs', default='1', - help="Number of parallel jobs.") -parser.add_argument('-R', '--tests-regex', dest='regex_tests', - help="Run tests matching regular expression. \ - Test names are the directories present in tests folder.\ - This uses standard regex syntax to select tests.") -parser.add_argument('-C', '--build-config', dest='build_config', - help="Build configurations matching regular expression. \ - Specific build configurations can be printed out with \ - optional argument -p, --print. This uses standard \ - regex syntax to select build configurations.") -parser.add_argument('-l', '--list', action="store_true", - dest="list_build_configs", default=False, - help="List out build configurations.") -parser.add_argument("-p", "--project", dest="project", default="", - help="project name for build") -parser.add_argument("-D", "--dashboard", dest="dash", - help="Dash name -- Experimental, Nightly, Continuous") -parser.add_argument("-u", "--update", action="store_true", dest="update", - help="Allow CTest to update repo. (WARNING: may overwrite\ - changes that were not pushed.") -parser.add_argument("-s", "--script", action="store_true", dest="script", - help="Activate CTest scripting mode for coverage, valgrind\ - and dashboard capability.") -args = parser.parse_args() - -# Default compiler paths -FC = 'gfortran' -CC = 'gcc' -CXX = 'g++' -MPI_DIR = '/opt/mpich/3.2-gnu' -HDF5_DIR = '/opt/hdf5/1.8.16-gnu' -PHDF5_DIR = '/opt/phdf5/1.8.16-gnu' - -# Script mode for extra capability -script_mode = False - -# Override default compiler paths if environmental vars are found -if 'FC' in os.environ: - FC = os.environ['FC'] -if 'CC' in os.environ: - CC = os.environ['CC'] -if 'CXX' in os.environ: - CXX = os.environ['CXX'] -if 'MPI_DIR' in os.environ: - MPI_DIR = os.environ['MPI_DIR'] -if 'HDF5_DIR' in os.environ: - HDF5_DIR = os.environ['HDF5_DIR'] -if 'PHDF5_DIR' in os.environ: - PHDF5_DIR = os.environ['PHDF5_DIR'] - -# CTest script template -ctest_str = """set (CTEST_SOURCE_DIRECTORY "{source_dir}") -set (CTEST_BINARY_DIRECTORY "{build_dir}") - -set(CTEST_SITE "{host_name}") -set (CTEST_BUILD_NAME "{build_name}") -set (CTEST_CMAKE_GENERATOR "Unix Makefiles") -set (CTEST_BUILD_OPTIONS "{build_opts}") - -set(CTEST_UPDATE_COMMAND "git") - -set(CTEST_CONFIGURE_COMMAND "${{CMAKE_COMMAND}} -H${{CTEST_SOURCE_DIRECTORY}} -B${{CTEST_BINARY_DIRECTORY}} ${{CTEST_BUILD_OPTIONS}}") -set(CTEST_MEMORYCHECK_COMMAND "{valgrind_cmd}") -set(CTEST_MEMORYCHECK_COMMAND_OPTIONS "--tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes") -#set(CTEST_MEMORYCHECK_SUPPRESSIONS_FILE ${{CTEST_SOURCE_DIRECTORY}}/../tests/valgrind.supp) -set(MEM_CHECK {mem_check}) -if(MEM_CHECK) -set(ENV{{MEM_CHECK}} ${{MEM_CHECK}}) -endif() - -set(CTEST_COVERAGE_COMMAND "gcov") -set(COVERAGE {coverage}) -set(ENV{{COVERAGE}} ${{COVERAGE}}) - -{subproject} - -ctest_start("{dashboard}") -ctest_configure(RETURN_VALUE res) -{update} -ctest_build(RETURN_VALUE res) -if(NOT MEM_CHECK) -ctest_test({tests} PARALLEL_LEVEL {n_procs}, RETURN_VALUE res) -endif() -if(MEM_CHECK) -ctest_memcheck({tests} RETURN_VALUE res) -endif(MEM_CHECK) -if(COVERAGE) -ctest_coverage(RETURN_VALUE res) -endif(COVERAGE) -{submit} - -if (res EQUAL 0) -else() -message(FATAL_ERROR "") -endif() -""" - -# Define test data structure -tests = OrderedDict() - - -def cleanup(path): - """Remove generated output files.""" - for dirpath, dirnames, filenames in os.walk(path): - for fname in filenames: - for ext in ['.h5', '.ppm', '.voxel']: - if fname.endswith(ext) and fname != '1d_mgxs.h5': - os.remove(os.path.join(dirpath, fname)) - - -def which(program): - def is_exe(fpath): - return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - - fpath, fname = os.path.split(program) - if fpath: - if is_exe(program): - return program - else: - for path in os.environ["PATH"].split(os.pathsep): - path = path.strip('"') - exe_file = os.path.join(path, program) - if is_exe(exe_file): - return exe_file - return None - - -class Test(object): - def __init__(self, name, debug=False, optimize=False, mpi=False, openmp=False, - phdf5=False, valgrind=False, coverage=False): - self.name = name - self.debug = debug - self.optimize = optimize - self.mpi = mpi - self.openmp = openmp - self.phdf5 = phdf5 - self.valgrind = valgrind - self.coverage = coverage - self.success = True - self.msg = None - self.skipped = False - self.cmake = ['cmake', '-H..', '-Bbuild', - '-DPYTHON_EXECUTABLE=' + sys.executable] - - # Check for MPI - if self.mpi: - if os.path.exists(os.path.join(MPI_DIR, 'bin', 'mpifort')): - self.fc = os.path.join(MPI_DIR, 'bin', 'mpifort') - else: - self.fc = os.path.join(MPI_DIR, 'bin', 'mpif90') - self.cc = os.path.join(MPI_DIR, 'bin', 'mpicc') - self.cxx = os.path.join(MPI_DIR, 'bin', 'mpicxx') - else: - self.fc = FC - self.cc = CC - self.cxx = CXX - - # Sets the build name that will show up on the CDash - def get_build_name(self): - self.build_name = args.project + '_' + self.name - return self.build_name - - # Sets up build options for various tests. It is used both - # in script and non-script modes - def get_build_opts(self): - build_str = "" - if self.debug: - build_str += "-Ddebug=ON " - if self.optimize: - build_str += "-Doptimize=ON " - if not self.openmp: - build_str += "-Dopenmp=OFF " - if self.coverage: - build_str += "-Dcoverage=ON " - if self.phdf5: - build_str += "-DHDF5_PREFER_PARALLEL=ON " - else: - build_str += "-DHDF5_PREFER_PARALLEL=OFF " - self.build_opts = build_str - return self.build_opts - - # Write out the ctest script to tests directory - def create_ctest_script(self, ctest_vars): - with open('ctestscript.run', 'w') as fh: - fh.write(ctest_str.format(**ctest_vars)) - - # Runs the ctest script which performs all the cmake/ctest/cdash - def run_ctest_script(self): - os.environ['FC'] = self.fc - os.environ['CC'] = self.cc - os.environ['CXX'] = self.cxx - if self.mpi: - os.environ['MPI_DIR'] = MPI_DIR - if self.phdf5: - os.environ['HDF5_ROOT'] = PHDF5_DIR - else: - os.environ['HDF5_ROOT'] = HDF5_DIR - rc = call(['ctest', '-S', 'ctestscript.run', '-V']) - if rc != 0: - self.success = False - self.msg = 'Failed on ctest script.' - - # Runs cmake when in non-script mode - def run_cmake(self): - build_opts = self.build_opts.split() - self.cmake += build_opts - - os.environ['FC'] = self.fc - os.environ['CC'] = self.cc - os.environ['CXX'] = self.cxx - if self.mpi: - os.environ['MPI_DIR'] = MPI_DIR - if self.phdf5: - os.environ['HDF5_ROOT'] = PHDF5_DIR - self.cmake.append('-DHDF5_PREFER_PARALLEL=ON') - else: - os.environ['HDF5_ROOT'] = HDF5_DIR - self.cmake.append('-DHDF5_PREFER_PARALLEL=OFF') - rc = call(self.cmake) - if rc != 0: - self.success = False - self.msg = 'Failed on cmake.' - - # Runs make when in non-script mode - def run_make(self): - if not self.success: - return - - # Default make string - make_list = ['make', '-s'] - - # Check for parallel - if args.n_procs is not None: - make_list.append('-j') - make_list.append(args.n_procs) - - # Run make - rc = call(make_list) - if rc != 0: - self.success = False - self.msg = 'Failed on make.' - - # Runs ctest when in non-script mode - def run_ctests(self): - if not self.success: - return - - # Default ctest string - ctest_list = ['ctest'] - - # Check for parallel - if args.n_procs is not None: - ctest_list.append('-j') - ctest_list.append(args.n_procs) - - # Check for subset of tests - if args.regex_tests is not None: - ctest_list.append('-R') - ctest_list.append(args.regex_tests) - - # Run ctests - rc = call(ctest_list) - if rc != 0: - self.success = False - self.msg = 'Failed on testing.' - - -# Simple function to add a test to the global tests dictionary -def add_test(name, debug=False, optimize=False, mpi=False, openmp=False, - phdf5=False, valgrind=False, coverage=False): - tests.update({name: Test(name, debug, optimize, mpi, openmp, phdf5, - valgrind, coverage)}) - -# List of all tests that may be run. User can add -C to command line to specify -# a subset of these configurations -add_test('hdf5-normal') -add_test('hdf5-debug', debug=True) -add_test('hdf5-optimize', optimize=True) -add_test('omp-hdf5-normal', openmp=True) -add_test('omp-hdf5-debug', openmp=True, debug=True) -add_test('omp-hdf5-optimize', openmp=True, optimize=True) -add_test('mpi-hdf5-normal', mpi=True) -add_test('mpi-hdf5-debug', mpi=True, debug=True) -add_test('mpi-hdf5-optimize', mpi=True, optimize=True) -add_test('phdf5-normal', mpi=True, phdf5=True) -add_test('phdf5-debug', mpi=True, phdf5=True, debug=True) -add_test('phdf5-optimize', mpi=True, phdf5=True, optimize=True) -add_test('phdf5-omp-normal', mpi=True, phdf5=True, openmp=True) -add_test('phdf5-omp-debug', mpi=True, phdf5=True, openmp=True, debug=True) -add_test('phdf5-omp-optimize', mpi=True, phdf5=True, openmp=True, optimize=True) -add_test('hdf5-debug_valgrind', debug=True, valgrind=True) -add_test('hdf5-debug_coverage', debug=True, coverage=True) - -# Check to see if we should just print build configuration information to user -if args.list_build_configs: - for key in tests: - print('Configuration Name: {0}'.format(key)) - print(' Debug Flags:..........{0}'.format(tests[key].debug)) - print(' Optimization Flags:...{0}'.format(tests[key].optimize)) - print(' MPI Active:...........{0}'.format(tests[key].mpi)) - print(' OpenMP Active:........{0}'.format(tests[key].openmp)) - print(' Valgrind Test:........{0}'.format(tests[key].valgrind)) - print(' Coverage Test:........{0}\n'.format(tests[key].coverage)) - exit() - -# Delete items of dictionary that don't match regular expression -if args.build_config is not None: - to_delete = [] - for key in tests: - if not re.search(args.build_config, key): - to_delete.append(key) - for key in to_delete: - del tests[key] - -# Check for dashboard and determine whether to push results to server -# Note that there are only 3 basic dashboards: -# Experimental, Nightly, Continuous. On the CDash end, these can be -# reorganized into groups when a hostname, dashboard and build name -# are matched. -if args.dash is None: - dash = 'Experimental' - submit = '' -else: - dash = args.dash - submit = 'ctest_submit()' - -# Check for update command, which will run git fetch/merge and will delete -# any changes to repo that were not pushed to remote origin -update = 'ctest_update()' if args.update else '' - -# Check for CTest scipts mode -# Sets up whether we should use just the basic ctest command or use -# CTest scripting to perform tests. -script_mode = (args.dash is not None or args.script) - -# Setup CTest script vars. Not used in non-script mode -pwd = os.getcwd() -ctest_vars = { - 'source_dir': os.path.join(pwd, os.pardir), - 'build_dir': os.path.join(pwd, 'build'), - 'host_name': socket.gethostname(), - 'dashboard': dash, - 'submit': submit, - 'update': update, - 'n_procs': args.n_procs -} - -# Check project name -subprop = "set_property(GLOBAL PROPERTY SubProject {0})" -if args.project == "": - ctest_vars.update({'subproject': ''}) -elif args.project == 'develop': - ctest_vars.update({'subproject': ''}) -else: - ctest_vars.update({'subproject': subprop.format(args.project)}) - -# Set up default valgrind tests (subset of all tests) -# Currently takes too long to run all the tests with valgrind -# Only used in script mode -valgrind_default_tests = "cmfd_feed|confidence_intervals|\ -density|eigenvalue_genperbatch|energy_grid|entropy|\ -lattice_multiple|output|plotreflective_plane|\ -rotation|salphabetascore_absorption|seed|source_energy_mono|\ -sourcepoint_batch|statepoint_interval|survival_biasing|\ -tally_assumesep|translation|uniform_fs|universe|void" - -# Delete items of dictionary if valgrind or coverage and not in script mode -to_delete = [] -if not script_mode: - for key in tests: - if re.search('valgrind|coverage', key): - to_delete.append(key) - -for key in to_delete: - del tests[key] - -# Check if tests is empty -if not tests: - print('No tests to run.') - exit() - -# Begin testing -shutil.rmtree('build', ignore_errors=True) -cleanup('.') -for key in iter(tests): - test = tests[key] - - # Extra display if not in script mode - if not script_mode: - print('-'*(len(key) + 6)) - print(key + ' tests') - print('-'*(len(key) + 6)) - sys.stdout.flush() - - # Verify fortran compiler exists - if which(test.fc) is None: - test.msg = 'Compiler not found: {0}'.format(test.fc) - test.success = False - continue - - # Verify valgrind command exists - if test.valgrind: - valgrind_cmd = which('valgrind') - if valgrind_cmd is None: - test.msg = 'No valgrind executable found.' - test.success = False - continue - else: - valgrind_cmd = '' - - # Verify gcov/lcov exist - if test.coverage: - if which('gcov') is None: - test.msg = 'No {} executable found.'.format(exe) - test.success = False - continue - - # Set test specific CTest script vars. Not used in non-script mode - ctest_vars.update({'build_name': test.get_build_name()}) - ctest_vars.update({'build_opts': test.get_build_opts()}) - ctest_vars.update({'mem_check': test.valgrind}) - ctest_vars.update({'coverage': test.coverage}) - ctest_vars.update({'valgrind_cmd': valgrind_cmd}) - - # Check for user custom tests - # INCLUDE is a CTest command that allows for a subset - # of tests to be executed. Only used in script mode. - if args.regex_tests is None: - ctest_vars.update({'tests': ''}) - - # No user tests, use default valgrind tests - if test.valgrind: - ctest_vars.update({'tests': 'INCLUDE {0}'. - format(valgrind_default_tests)}) - else: - ctest_vars.update({'tests': 'INCLUDE {0}'. - format(args.regex_tests)}) - - # Main part of code that does the ctest execution. - # It is broken up by two modes, script and non-script - if script_mode: - - # Create ctest script - test.create_ctest_script(ctest_vars) - - # Run test - test.run_ctest_script() - - else: - - # Run CMAKE to configure build - test.run_cmake() - - # Go into build directory - os.chdir('build') - - # Build OpenMC - test.run_make() - - # Run tests - test.run_ctests() - - # Leave build directory - os.chdir(os.pardir) - - # Copy over log file - if script_mode: - logfile = glob.glob('build/Testing/Temporary/LastTest_*.log') - else: - logfile = glob.glob('build/Testing/Temporary/LastTest.log') - if len(logfile) > 0: - logfilename = os.path.split(logfile[0])[1] - logfilename = os.path.splitext(logfilename)[0] - logfilename = logfilename + '_{0}.log'.format(test.name) - shutil.copy(logfile[0], logfilename) - - # For coverage builds, use lcov to generate HTML output - if test.coverage: - if which('lcov') is None or which('genhtml') is None: - print('No lcov/genhtml command found. ' - 'Could not generate coverage report.') - else: - shutil.rmtree('coverage', ignore_errors=True) - call(['lcov', '--directory', '.', '--capture', - '--output-file', 'coverage.info']) - call(['genhtml', '--output-directory', 'coverage', 'coverage.info']) - os.remove('coverage.info') - - if test.valgrind: - # Copy memcheck output to memcheck directory - shutil.rmtree('memcheck', ignore_errors=True) - os.mkdir('memcheck') - memcheck_out = glob.glob('build/Testing/Temporary/MemoryChecker.*.log') - for fname in memcheck_out: - shutil.copy(fname, 'memcheck/') - - # Remove generated XML files - xml_files = check_output(['git', 'ls-files', '.', '--exclude-standard', - '--others']).split() - for f in xml_files: - os.remove(f) - - # Clear build directory and remove binary and hdf5 files - shutil.rmtree('build', ignore_errors=True) - if script_mode: - os.remove('ctestscript.run') - cleanup('.') - -# Print out summary of results -print('\n' + '='*54) -print('Summary of Compilation Option Testing:\n') - -if sys.stdout.isatty(): - OK = '\033[92m' - FAIL = '\033[91m' - ENDC = '\033[0m' - BOLD = '\033[1m' -else: - OK = '' - FAIL = '' - ENDC = '' - BOLD = '' - -return_code = 0 - -for test in tests: - print(test + '.'*(50 - len(test)), end='') - if tests[test].success: - print(BOLD + OK + '[OK]' + ENDC) - else: - print(BOLD + FAIL + '[FAILED]' + ENDC) - print(' '*len(test)+tests[test].msg) - return_code = 1 - -sys.exit(return_code) diff --git a/tools/ci/travis-install.py b/tools/ci/travis-install.py new file mode 100644 index 0000000000..0e4dbdc01b --- /dev/null +++ b/tools/ci/travis-install.py @@ -0,0 +1,65 @@ +import os +import shutil +import subprocess + + +def which(program): + def is_exe(fpath): + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) + + fpath, fname = os.path.split(program) + if fpath: + if is_exe(program): + return program + else: + for path in os.environ["PATH"].split(os.pathsep): + path = path.strip('"') + exe_file = os.path.join(path, program) + if is_exe(exe_file): + return exe_file + return None + + +def install(omp=False, mpi=False, phdf5=False): + # Create build directory and change to it + shutil.rmtree('build', ignore_errors=True) + os.mkdir('build') + os.chdir('build') + + # Build in debug mode by default + cmake_cmd = ['cmake', '-Ddebug=on'] + + # Turn off OpenMP if specified + if not omp: + cmake_cmd.append('-Dopenmp=off') + + # For MPI, we just need to change the Fortran compiler + if mpi: + os.environ['FC'] = 'mpifort' if which('mpifort') else 'mpif90' + + # Tell CMake to prefer parallel HDF5 if specified + if phdf5: + if not mpi: + raise ValueError('Parallel HDF5 must be used in ' + 'conjunction with MPI.') + cmake_cmd.append('-DHDF5_PREFER_PARALLEL=on') + + # Build and install + cmake_cmd.append('..') + subprocess.call(cmake_cmd) + subprocess.call(['make', '-j']) + subprocess.call(['make', 'install']) + + +def main(): + # Convert Travis matrix environment variables into arguments for install() + omp = (os.environ.get('OMP') == 'y') + mpi = (os.environ.get('MPI') == 'y') + phdf5 = (os.environ.get('PHDF5') == 'y') + + # Build and install + install(omp, mpi, phdf5) + + +if __name__ == '__main__': + main() diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 354ae7f7f4..6051f03aa9 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -15,5 +15,8 @@ if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then pip install pandas==0.20.3 fi +# Build and install +python tools/ci/travis-install.py + # Install OpenMC in editable mode pip install -e .[test] diff --git a/tools/ci/travis-script.sh b/tools/ci/travis-script.sh index 978a2811c4..2934cb59a0 100755 --- a/tools/ci/travis-script.sh +++ b/tools/ci/travis-script.sh @@ -1,8 +1,15 @@ #!/bin/bash set -ex -cd tests -if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OPENMC_CONFIG == '^hdf5-debug$' ]]; then + +# Run regression test suite +cd build +ctest + +# Run source check +cd ../tests +if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OMP == 'n' && $MPI == 'n' ]]; then ./check_source.py fi -./run_tests.py -C $OPENMC_CONFIG -j 2 + +# Run unit tests pytest --cov=../openmc -v unit_tests/ From c3af1c915b8b799ce59ec1accd124a1595c0cd41 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 28 Jan 2018 15:08:24 -0600 Subject: [PATCH 047/212] Move regression tests into separate directory --- CMakeLists.txt | 8 ++++---- openmc/examples.py | 2 +- .../asymmetric_lattice}/inputs_true.dat | 0 .../asymmetric_lattice}/results_true.dat | 0 .../asymmetric_lattice/test.py} | 2 +- .../cmfd_feed}/cmfd.xml | 0 .../cmfd_feed}/geometry.xml | 0 .../cmfd_feed}/materials.xml | 0 .../cmfd_feed}/results_true.dat | 0 .../cmfd_feed}/settings.xml | 0 .../cmfd_feed}/tallies.xml | 0 .../cmfd_feed/test.py} | 2 +- .../cmfd_nofeed}/cmfd.xml | 0 .../cmfd_nofeed}/geometry.xml | 0 .../cmfd_nofeed}/materials.xml | 0 .../cmfd_nofeed}/results_true.dat | 0 .../cmfd_nofeed}/settings.xml | 0 .../cmfd_nofeed}/tallies.xml | 0 .../cmfd_nofeed/test.py} | 2 +- .../complex_cell}/geometry.xml | 0 .../complex_cell}/materials.xml | 0 .../complex_cell}/results_true.dat | 0 .../complex_cell}/settings.xml | 0 .../complex_cell}/tallies.xml | 0 .../complex_cell/test.py} | 2 +- .../confidence_intervals}/geometry.xml | 0 .../confidence_intervals}/materials.xml | 0 .../confidence_intervals}/results_true.dat | 0 .../confidence_intervals}/settings.xml | 0 .../confidence_intervals}/tallies.xml | 0 .../confidence_intervals/test.py} | 2 +- .../create_fission_neutrons}/inputs_true.dat | 0 .../create_fission_neutrons}/results_true.dat | 0 .../create_fission_neutrons/test.py} | 2 +- .../density}/geometry.xml | 0 .../density}/materials.xml | 0 .../density}/results_true.dat | 0 .../density}/settings.xml | 0 .../density/test.py} | 2 +- .../diff_tally}/inputs_true.dat | 0 .../diff_tally}/results_true.dat | 0 .../diff_tally/test.py} | 2 +- .../distribmat}/inputs_true.dat | 0 .../distribmat}/results_true.dat | 0 .../distribmat/test.py} | 2 +- .../eigenvalue_genperbatch}/geometry.xml | 0 .../eigenvalue_genperbatch}/materials.xml | 0 .../eigenvalue_genperbatch}/results_true.dat | 0 .../eigenvalue_genperbatch}/settings.xml | 0 .../eigenvalue_genperbatch/test.py} | 2 +- .../eigenvalue_no_inactive}/geometry.xml | 0 .../eigenvalue_no_inactive}/materials.xml | 0 .../eigenvalue_no_inactive}/results_true.dat | 0 .../eigenvalue_no_inactive}/settings.xml | 0 .../eigenvalue_no_inactive/test.py} | 2 +- .../energy_cutoff}/inputs_true.dat | 0 .../energy_cutoff}/results_true.dat | 0 .../energy_cutoff/test.py} | 2 +- .../energy_grid}/geometry.xml | 0 .../energy_grid}/materials.xml | 0 .../energy_grid}/results_true.dat | 0 .../energy_grid}/settings.xml | 0 tests/regression_tests/energy_grid/test.py | 11 +++++++++++ .../energy_laws}/geometry.xml | 0 .../energy_laws}/materials.xml | 0 .../energy_laws}/results_true.dat | 0 .../energy_laws}/settings.xml | 0 .../energy_laws/test.py} | 2 +- .../enrichment/test.py} | 1 - .../entropy}/geometry.xml | 0 .../entropy}/materials.xml | 0 .../entropy}/results_true.dat | 0 .../entropy}/settings.xml | 0 .../entropy/test.py} | 2 +- .../filter_distribcell}/case-1/geometry.xml | 0 .../filter_distribcell}/case-1/materials.xml | 0 .../filter_distribcell}/case-1/results_true.dat | 0 .../filter_distribcell}/case-1/settings.xml | 0 .../filter_distribcell}/case-1/tallies.xml | 0 .../filter_distribcell}/case-2/geometry.xml | 0 .../filter_distribcell}/case-2/materials.xml | 0 .../filter_distribcell}/case-2/results_true.dat | 0 .../filter_distribcell}/case-2/settings.xml | 0 .../filter_distribcell}/case-2/tallies.xml | 0 .../filter_distribcell}/case-3/geometry.xml | 0 .../filter_distribcell}/case-3/materials.xml | 0 .../filter_distribcell}/case-3/results_true.dat | 0 .../filter_distribcell}/case-3/settings.xml | 0 .../filter_distribcell}/case-3/tallies.xml | 0 .../filter_distribcell}/case-4/geometry.xml | 0 .../filter_distribcell}/case-4/materials.xml | 0 .../filter_distribcell}/case-4/results_true.dat | 0 .../filter_distribcell}/case-4/settings.xml | 0 .../filter_distribcell}/case-4/tallies.xml | 0 .../filter_distribcell/test.py} | 2 +- .../filter_energyfun}/inputs_true.dat | 0 .../filter_energyfun}/results_true.dat | 0 .../filter_energyfun/test.py} | 2 +- .../filter_mesh}/inputs_true.dat | 0 .../filter_mesh}/results_true.dat | 0 .../filter_mesh/test.py} | 2 +- .../fixed_source}/inputs_true.dat | 0 .../fixed_source}/results_true.dat | 0 .../fixed_source/test.py} | 2 +- .../infinite_cell}/geometry.xml | 0 .../infinite_cell}/materials.xml | 0 .../infinite_cell}/results_true.dat | 0 .../infinite_cell}/settings.xml | 0 tests/regression_tests/infinite_cell/test.py | 11 +++++++++++ .../iso_in_lab}/inputs_true.dat | 0 .../iso_in_lab}/results_true.dat | 0 .../iso_in_lab/test.py} | 2 +- .../lattice}/geometry.xml | 0 .../lattice}/materials.xml | 0 .../lattice}/results_true.dat | 0 .../lattice}/settings.xml | 0 tests/regression_tests/lattice/test.py | 11 +++++++++++ .../lattice_hex}/geometry.xml | 0 .../lattice_hex}/materials.xml | 0 .../lattice_hex}/plots.xml | 0 .../lattice_hex}/results_true.dat | 0 .../lattice_hex}/settings.xml | 0 tests/regression_tests/lattice_hex/test.py | 11 +++++++++++ .../lattice_mixed}/geometry.xml | 0 .../lattice_mixed}/materials.xml | 0 .../lattice_mixed}/plots.xml | 0 .../lattice_mixed}/results_true.dat | 0 .../lattice_mixed}/settings.xml | 0 tests/regression_tests/lattice_mixed/test.py | 11 +++++++++++ .../lattice_multiple}/geometry.xml | 0 .../lattice_multiple}/materials.xml | 0 .../lattice_multiple}/results_true.dat | 0 .../lattice_multiple}/settings.xml | 0 tests/regression_tests/lattice_multiple/test.py | 11 +++++++++++ .../mg_basic}/inputs_true.dat | 2 +- .../mg_basic}/results_true.dat | 0 .../mg_basic/test.py} | 2 +- .../mg_convert}/inputs_true.dat | 0 .../mg_convert}/results_true.dat | 0 .../mg_convert/test.py} | 2 +- .../mg_legendre}/inputs_true.dat | 2 +- .../mg_legendre}/results_true.dat | 0 .../mg_legendre/test.py} | 2 +- .../mg_max_order}/inputs_true.dat | 2 +- .../mg_max_order}/results_true.dat | 0 .../mg_max_order/test.py} | 2 +- .../mg_nuclide}/inputs_true.dat | 2 +- .../mg_nuclide}/results_true.dat | 0 .../mg_nuclide/test.py} | 2 +- .../mg_survival_biasing}/inputs_true.dat | 2 +- .../mg_survival_biasing}/results_true.dat | 0 .../mg_survival_biasing/test.py} | 2 +- .../mg_tallies}/inputs_true.dat | 2 +- .../mg_tallies}/results_true.dat | 0 .../mg_tallies/test.py} | 2 +- .../mgxs_library_ce_to_mg}/inputs_true.dat | 0 .../mgxs_library_ce_to_mg}/results_true.dat | 0 .../mgxs_library_ce_to_mg/test.py} | 2 +- .../mgxs_library_condense}/inputs_true.dat | 0 .../mgxs_library_condense}/results_true.dat | 0 .../mgxs_library_condense/test.py} | 2 +- .../mgxs_library_distribcell}/inputs_true.dat | 0 .../mgxs_library_distribcell}/results_true.dat | 0 .../mgxs_library_distribcell/test.py} | 2 +- .../mgxs_library_hdf5}/inputs_true.dat | 0 .../mgxs_library_hdf5}/results_true.dat | 0 .../mgxs_library_hdf5/test.py} | 2 +- .../mgxs_library_mesh}/inputs_true.dat | 0 .../mgxs_library_mesh}/results_true.dat | 0 .../mgxs_library_mesh/test.py} | 2 +- .../mgxs_library_no_nuclides}/inputs_true.dat | 0 .../mgxs_library_no_nuclides}/results_true.dat | 0 .../mgxs_library_no_nuclides/test.py} | 2 +- .../mgxs_library_nuclides}/inputs_true.dat | 0 .../mgxs_library_nuclides}/results_true.dat | 0 .../mgxs_library_nuclides/test.py} | 2 +- .../multipole}/inputs_true.dat | 0 .../multipole}/results_true.dat | 0 .../multipole/test.py} | 2 +- .../output}/geometry.xml | 0 .../output}/materials.xml | 0 .../output}/results_true.dat | 0 .../output}/settings.xml | 0 .../output/test.py} | 2 +- .../particle_restart_eigval}/geometry.xml | 0 .../particle_restart_eigval}/materials.xml | 0 .../particle_restart_eigval}/results_true.dat | 0 .../particle_restart_eigval}/settings.xml | 0 .../particle_restart_eigval/test.py} | 2 +- .../particle_restart_fixed}/geometry.xml | 0 .../particle_restart_fixed}/materials.xml | 0 .../particle_restart_fixed}/results_true.dat | 0 .../particle_restart_fixed}/settings.xml | 0 .../particle_restart_fixed/test.py} | 2 +- .../periodic}/inputs_true.dat | 0 .../periodic}/results_true.dat | 0 .../periodic/test.py} | 2 +- .../{test_plot => regression_tests/plot}/geometry.xml | 0 .../plot}/materials.xml | 0 tests/{test_plot => regression_tests/plot}/plots.xml | 0 .../plot}/results_true.dat | 0 .../{test_plot => regression_tests/plot}/settings.xml | 0 .../test_plot.py => regression_tests/plot/test.py} | 2 +- .../ptables_off}/geometry.xml | 0 .../ptables_off}/materials.xml | 0 .../ptables_off}/results_true.dat | 0 .../ptables_off}/settings.xml | 0 tests/regression_tests/ptables_off/test.py | 11 +++++++++++ .../quadric_surfaces}/geometry.xml | 0 .../quadric_surfaces}/materials.xml | 0 .../quadric_surfaces}/results_true.dat | 0 .../quadric_surfaces}/settings.xml | 0 tests/regression_tests/quadric_surfaces/test.py | 11 +++++++++++ .../reflective_plane}/geometry.xml | 0 .../reflective_plane}/materials.xml | 0 .../reflective_plane}/results_true.dat | 0 .../reflective_plane}/settings.xml | 0 tests/regression_tests/reflective_plane/test.py | 11 +++++++++++ .../resonance_scattering}/inputs_true.dat | 0 .../resonance_scattering}/results_true.dat | 0 .../resonance_scattering/test.py} | 2 +- .../rotation}/geometry.xml | 0 .../rotation}/materials.xml | 0 .../rotation}/results_true.dat | 0 .../rotation}/settings.xml | 0 tests/regression_tests/rotation/test.py | 11 +++++++++++ .../salphabeta}/inputs_true.dat | 0 .../salphabeta}/results_true.dat | 0 .../salphabeta/test.py} | 2 +- .../score_current}/geometry.xml | 0 .../score_current}/materials.xml | 0 .../score_current}/results_true.dat | 0 .../score_current}/settings.xml | 0 .../score_current}/tallies.xml | 0 .../score_current/test.py} | 2 +- .../{test_seed => regression_tests/seed}/geometry.xml | 0 .../seed}/materials.xml | 0 .../seed}/results_true.dat | 0 .../{test_seed => regression_tests/seed}/settings.xml | 0 tests/regression_tests/seed/test.py | 11 +++++++++++ .../source}/inputs_true.dat | 0 .../source}/results_true.dat | 0 .../source/test.py} | 2 +- .../source_file}/geometry.xml | 0 .../source_file}/materials.xml | 0 .../source_file}/results_true.dat | 0 .../source_file}/settings.xml | 0 .../source_file/test.py} | 2 +- .../sourcepoint_batch}/geometry.xml | 0 .../sourcepoint_batch}/materials.xml | 0 .../sourcepoint_batch}/results_true.dat | 0 .../sourcepoint_batch}/settings.xml | 0 .../sourcepoint_batch/test.py} | 2 +- .../sourcepoint_latest}/geometry.xml | 0 .../sourcepoint_latest}/materials.xml | 0 .../sourcepoint_latest}/results_true.dat | 0 .../sourcepoint_latest}/settings.xml | 0 .../sourcepoint_latest/test.py} | 2 +- .../sourcepoint_restart}/geometry.xml | 0 .../sourcepoint_restart}/materials.xml | 0 .../sourcepoint_restart}/results_true.dat | 0 .../sourcepoint_restart}/settings.xml | 0 .../sourcepoint_restart}/tallies.xml | 0 tests/regression_tests/sourcepoint_restart/test.py | 11 +++++++++++ .../statepoint_batch}/geometry.xml | 0 .../statepoint_batch}/materials.xml | 0 .../statepoint_batch}/results_true.dat | 0 .../statepoint_batch}/settings.xml | 0 .../statepoint_batch/test.py} | 2 +- .../statepoint_restart}/geometry.xml | 0 .../statepoint_restart}/materials.xml | 0 .../statepoint_restart}/results_true.dat | 0 .../statepoint_restart}/settings.xml | 0 .../statepoint_restart}/tallies.xml | 0 .../statepoint_restart/test.py} | 2 +- .../statepoint_sourcesep}/geometry.xml | 0 .../statepoint_sourcesep}/materials.xml | 0 .../statepoint_sourcesep}/results_true.dat | 0 .../statepoint_sourcesep}/settings.xml | 0 .../statepoint_sourcesep/test.py} | 2 +- .../surface_tally}/inputs_true.dat | 0 .../surface_tally}/results_true.dat | 0 .../surface_tally/test.py} | 2 +- .../survival_biasing}/geometry.xml | 0 .../survival_biasing}/materials.xml | 0 .../survival_biasing}/results_true.dat | 0 .../survival_biasing}/settings.xml | 0 .../survival_biasing}/tallies.xml | 0 tests/regression_tests/survival_biasing/test.py | 11 +++++++++++ .../tallies}/inputs_true.dat | 0 .../tallies}/results_true.dat | 0 .../tallies/test.py} | 2 +- .../tally_aggregation}/inputs_true.dat | 0 .../tally_aggregation}/results_true.dat | 0 .../tally_aggregation/test.py} | 2 +- .../tally_arithmetic}/inputs_true.dat | 0 .../tally_arithmetic}/results_true.dat | 0 .../tally_arithmetic/test.py} | 2 +- .../tally_assumesep}/geometry.xml | 0 .../tally_assumesep}/materials.xml | 0 .../tally_assumesep}/results_true.dat | 0 .../tally_assumesep}/settings.xml | 0 .../tally_assumesep}/tallies.xml | 0 tests/regression_tests/tally_assumesep/test.py | 11 +++++++++++ .../tally_nuclides}/geometry.xml | 0 .../tally_nuclides}/materials.xml | 0 .../tally_nuclides}/results_true.dat | 0 .../tally_nuclides}/settings.xml | 0 .../tally_nuclides}/tallies.xml | 0 tests/regression_tests/tally_nuclides/test.py | 11 +++++++++++ .../tally_slice_merge}/inputs_true.dat | 0 .../tally_slice_merge}/results_true.dat | 0 .../tally_slice_merge/test.py} | 2 +- .../trace}/geometry.xml | 0 .../trace}/materials.xml | 0 .../trace}/results_true.dat | 0 .../trace}/settings.xml | 0 tests/regression_tests/trace/test.py | 11 +++++++++++ .../track_output}/geometry.xml | 0 .../track_output}/materials.xml | 0 .../track_output}/results_true.dat | 0 .../track_output}/settings.xml | 0 .../track_output/test.py} | 2 +- .../translation}/geometry.xml | 0 .../translation}/materials.xml | 0 .../translation}/results_true.dat | 0 .../translation}/settings.xml | 0 tests/regression_tests/translation/test.py | 11 +++++++++++ .../trigger_batch_interval}/geometry.xml | 0 .../trigger_batch_interval}/materials.xml | 0 .../trigger_batch_interval}/results_true.dat | 0 .../trigger_batch_interval}/settings.xml | 0 .../trigger_batch_interval}/tallies.xml | 0 .../trigger_batch_interval/test.py} | 2 +- .../trigger_no_batch_interval}/geometry.xml | 0 .../trigger_no_batch_interval}/materials.xml | 0 .../trigger_no_batch_interval}/results_true.dat | 0 .../trigger_no_batch_interval}/settings.xml | 0 .../trigger_no_batch_interval}/tallies.xml | 0 .../trigger_no_batch_interval/test.py} | 2 +- .../trigger_no_status}/geometry.xml | 0 .../trigger_no_status}/materials.xml | 0 .../trigger_no_status}/results_true.dat | 0 .../trigger_no_status}/settings.xml | 0 .../trigger_no_status}/tallies.xml | 0 tests/regression_tests/trigger_no_status/test.py | 11 +++++++++++ .../trigger_tallies}/geometry.xml | 0 .../trigger_tallies}/materials.xml | 0 .../trigger_tallies}/results_true.dat | 0 .../trigger_tallies}/settings.xml | 0 .../trigger_tallies}/tallies.xml | 0 .../trigger_tallies/test.py} | 2 +- .../triso}/inputs_true.dat | 0 .../triso}/results_true.dat | 0 .../test_triso.py => regression_tests/triso/test.py} | 2 +- .../uniform_fs}/geometry.xml | 0 .../uniform_fs}/materials.xml | 0 .../uniform_fs}/results_true.dat | 0 .../uniform_fs}/settings.xml | 0 tests/regression_tests/uniform_fs/test.py | 11 +++++++++++ .../universe}/geometry.xml | 0 .../universe}/materials.xml | 0 .../universe}/results_true.dat | 0 .../universe}/settings.xml | 0 tests/regression_tests/universe/test.py | 11 +++++++++++ .../{test_void => regression_tests/void}/geometry.xml | 0 .../void}/materials.xml | 0 .../void}/results_true.dat | 0 .../{test_void => regression_tests/void}/settings.xml | 0 tests/regression_tests/void/test.py | 11 +++++++++++ .../volume_calc}/inputs_true.dat | 0 .../volume_calc}/results_true.dat | 0 .../volume_calc/test.py} | 2 +- tests/test_complex_cell/test_complex_cell.py | 10 ---------- tests/test_infinite_cell/test_infinite_cell.py | 11 ----------- tests/test_lattice/test_lattice.py | 11 ----------- tests/test_lattice_hex/test_lattice_hex.py | 11 ----------- tests/test_lattice_mixed/test_lattice_mixed.py | 11 ----------- tests/test_lattice_multiple/test_lattice_multiple.py | 11 ----------- tests/test_ptables_off/test_ptables_off.py | 11 ----------- tests/test_quadric_surfaces/test_quadric_surfaces.py | 11 ----------- tests/test_reflective_plane/test_reflective_plane.py | 11 ----------- tests/test_rotation/test_rotation.py | 11 ----------- tests/test_seed/test_seed.py | 11 ----------- .../test_sourcepoint_restart.py | 11 ----------- tests/test_survival_biasing/test_survival_biasing.py | 11 ----------- tests/test_tally_assumesep/test_tally_assumesep.py | 11 ----------- tests/test_tally_nuclides/test_tally_nuclides.py | 11 ----------- tests/test_trace/test_trace.py | 11 ----------- tests/test_translation/test_translation.py | 11 ----------- .../test_trigger_no_status/test_trigger_no_status.py | 11 ----------- tests/test_uniform_fs/test_uniform_fs.py | 11 ----------- tests/test_universe/test_universe.py | 11 ----------- tests/test_void/test_void.py | 11 ----------- 394 files changed, 302 insertions(+), 302 deletions(-) rename tests/{test_asymmetric_lattice => regression_tests/asymmetric_lattice}/inputs_true.dat (100%) rename tests/{test_asymmetric_lattice => regression_tests/asymmetric_lattice}/results_true.dat (100%) rename tests/{test_asymmetric_lattice/test_asymmetric_lattice.py => regression_tests/asymmetric_lattice/test.py} (98%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/cmfd.xml (100%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/geometry.xml (100%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/materials.xml (100%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/results_true.dat (100%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/settings.xml (100%) rename tests/{test_cmfd_feed => regression_tests/cmfd_feed}/tallies.xml (100%) rename tests/{test_cmfd_feed/test_cmfd_feed.py => regression_tests/cmfd_feed/test.py} (77%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/cmfd.xml (100%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/geometry.xml (100%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/materials.xml (100%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/results_true.dat (100%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/settings.xml (100%) rename tests/{test_cmfd_nofeed => regression_tests/cmfd_nofeed}/tallies.xml (100%) rename tests/{test_cmfd_nofeed/test_cmfd_nofeed.py => regression_tests/cmfd_nofeed/test.py} (77%) rename tests/{test_complex_cell => regression_tests/complex_cell}/geometry.xml (100%) rename tests/{test_complex_cell => regression_tests/complex_cell}/materials.xml (100%) rename tests/{test_complex_cell => regression_tests/complex_cell}/results_true.dat (100%) rename tests/{test_complex_cell => regression_tests/complex_cell}/settings.xml (100%) rename tests/{test_complex_cell => regression_tests/complex_cell}/tallies.xml (100%) rename tests/{test_confidence_intervals/test_confidence_intervals.py => regression_tests/complex_cell/test.py} (76%) rename tests/{test_confidence_intervals => regression_tests/confidence_intervals}/geometry.xml (100%) rename tests/{test_confidence_intervals => regression_tests/confidence_intervals}/materials.xml (100%) rename tests/{test_confidence_intervals => regression_tests/confidence_intervals}/results_true.dat (100%) rename tests/{test_confidence_intervals => regression_tests/confidence_intervals}/settings.xml (100%) rename tests/{test_confidence_intervals => regression_tests/confidence_intervals}/tallies.xml (100%) rename tests/{test_density/test_density.py => regression_tests/confidence_intervals/test.py} (76%) mode change 100644 => 100755 rename tests/{test_create_fission_neutrons => regression_tests/create_fission_neutrons}/inputs_true.dat (100%) rename tests/{test_create_fission_neutrons => regression_tests/create_fission_neutrons}/results_true.dat (100%) rename tests/{test_create_fission_neutrons/test_create_fission_neutrons.py => regression_tests/create_fission_neutrons/test.py} (97%) rename tests/{test_density => regression_tests/density}/geometry.xml (100%) rename tests/{test_density => regression_tests/density}/materials.xml (100%) rename tests/{test_density => regression_tests/density}/results_true.dat (100%) rename tests/{test_density => regression_tests/density}/settings.xml (100%) rename tests/{test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py => regression_tests/density/test.py} (76%) rename tests/{test_diff_tally => regression_tests/diff_tally}/inputs_true.dat (100%) rename tests/{test_diff_tally => regression_tests/diff_tally}/results_true.dat (100%) rename tests/{test_diff_tally/test_diff_tally.py => regression_tests/diff_tally/test.py} (98%) rename tests/{test_distribmat => regression_tests/distribmat}/inputs_true.dat (100%) rename tests/{test_distribmat => regression_tests/distribmat}/results_true.dat (100%) rename tests/{test_distribmat/test_distribmat.py => regression_tests/distribmat/test.py} (98%) rename tests/{test_eigenvalue_genperbatch => regression_tests/eigenvalue_genperbatch}/geometry.xml (100%) rename tests/{test_eigenvalue_genperbatch => regression_tests/eigenvalue_genperbatch}/materials.xml (100%) rename tests/{test_eigenvalue_genperbatch => regression_tests/eigenvalue_genperbatch}/results_true.dat (100%) rename tests/{test_eigenvalue_genperbatch => regression_tests/eigenvalue_genperbatch}/settings.xml (100%) rename tests/{test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py => regression_tests/eigenvalue_genperbatch/test.py} (76%) rename tests/{test_eigenvalue_no_inactive => regression_tests/eigenvalue_no_inactive}/geometry.xml (100%) rename tests/{test_eigenvalue_no_inactive => regression_tests/eigenvalue_no_inactive}/materials.xml (100%) rename tests/{test_eigenvalue_no_inactive => regression_tests/eigenvalue_no_inactive}/results_true.dat (100%) rename tests/{test_eigenvalue_no_inactive => regression_tests/eigenvalue_no_inactive}/settings.xml (100%) rename tests/{test_energy_grid/test_energy_grid.py => regression_tests/eigenvalue_no_inactive/test.py} (76%) rename tests/{test_energy_cutoff => regression_tests/energy_cutoff}/inputs_true.dat (100%) rename tests/{test_energy_cutoff => regression_tests/energy_cutoff}/results_true.dat (100%) rename tests/{test_energy_cutoff/test_energy_cutoff.py => regression_tests/energy_cutoff/test.py} (97%) rename tests/{test_energy_grid => regression_tests/energy_grid}/geometry.xml (100%) rename tests/{test_energy_grid => regression_tests/energy_grid}/materials.xml (100%) rename tests/{test_energy_grid => regression_tests/energy_grid}/results_true.dat (100%) rename tests/{test_energy_grid => regression_tests/energy_grid}/settings.xml (100%) create mode 100644 tests/regression_tests/energy_grid/test.py rename tests/{test_energy_laws => regression_tests/energy_laws}/geometry.xml (100%) rename tests/{test_energy_laws => regression_tests/energy_laws}/materials.xml (100%) rename tests/{test_energy_laws => regression_tests/energy_laws}/results_true.dat (100%) rename tests/{test_energy_laws => regression_tests/energy_laws}/settings.xml (100%) rename tests/{test_energy_laws/test_energy_laws.py => regression_tests/energy_laws/test.py} (93%) rename tests/{test_enrichment/test_enrichment.py => regression_tests/enrichment/test.py} (97%) rename tests/{test_entropy => regression_tests/entropy}/geometry.xml (100%) rename tests/{test_entropy => regression_tests/entropy}/materials.xml (100%) rename tests/{test_entropy => regression_tests/entropy}/results_true.dat (100%) rename tests/{test_entropy => regression_tests/entropy}/settings.xml (100%) rename tests/{test_entropy/test_entropy.py => regression_tests/entropy/test.py} (94%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-1/geometry.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-1/materials.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-1/results_true.dat (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-1/settings.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-1/tallies.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-2/geometry.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-2/materials.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-2/results_true.dat (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-2/settings.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-2/tallies.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-3/geometry.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-3/materials.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-3/results_true.dat (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-3/settings.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-3/tallies.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-4/geometry.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-4/materials.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-4/results_true.dat (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-4/settings.xml (100%) rename tests/{test_filter_distribcell => regression_tests/filter_distribcell}/case-4/tallies.xml (100%) rename tests/{test_filter_distribcell/test_filter_distribcell.py => regression_tests/filter_distribcell/test.py} (98%) rename tests/{test_filter_energyfun => regression_tests/filter_energyfun}/inputs_true.dat (100%) rename tests/{test_filter_energyfun => regression_tests/filter_energyfun}/results_true.dat (100%) rename tests/{test_filter_energyfun/test_filter_energyfun.py => regression_tests/filter_energyfun/test.py} (97%) rename tests/{test_filter_mesh => regression_tests/filter_mesh}/inputs_true.dat (100%) rename tests/{test_filter_mesh => regression_tests/filter_mesh}/results_true.dat (100%) rename tests/{test_filter_mesh/test_filter_mesh.py => regression_tests/filter_mesh/test.py} (97%) rename tests/{test_fixed_source => regression_tests/fixed_source}/inputs_true.dat (100%) rename tests/{test_fixed_source => regression_tests/fixed_source}/results_true.dat (100%) rename tests/{test_fixed_source/test_fixed_source.py => regression_tests/fixed_source/test.py} (97%) rename tests/{test_infinite_cell => regression_tests/infinite_cell}/geometry.xml (100%) rename tests/{test_infinite_cell => regression_tests/infinite_cell}/materials.xml (100%) rename tests/{test_infinite_cell => regression_tests/infinite_cell}/results_true.dat (100%) rename tests/{test_infinite_cell => regression_tests/infinite_cell}/settings.xml (100%) create mode 100644 tests/regression_tests/infinite_cell/test.py rename tests/{test_iso_in_lab => regression_tests/iso_in_lab}/inputs_true.dat (100%) rename tests/{test_iso_in_lab => regression_tests/iso_in_lab}/results_true.dat (100%) rename tests/{test_iso_in_lab/test_iso_in_lab.py => regression_tests/iso_in_lab/test.py} (83%) rename tests/{test_lattice => regression_tests/lattice}/geometry.xml (100%) rename tests/{test_lattice => regression_tests/lattice}/materials.xml (100%) rename tests/{test_lattice => regression_tests/lattice}/results_true.dat (100%) rename tests/{test_lattice => regression_tests/lattice}/settings.xml (100%) create mode 100644 tests/regression_tests/lattice/test.py rename tests/{test_lattice_hex => regression_tests/lattice_hex}/geometry.xml (100%) rename tests/{test_lattice_hex => regression_tests/lattice_hex}/materials.xml (100%) rename tests/{test_lattice_hex => regression_tests/lattice_hex}/plots.xml (100%) rename tests/{test_lattice_hex => regression_tests/lattice_hex}/results_true.dat (100%) rename tests/{test_lattice_hex => regression_tests/lattice_hex}/settings.xml (100%) create mode 100644 tests/regression_tests/lattice_hex/test.py rename tests/{test_lattice_mixed => regression_tests/lattice_mixed}/geometry.xml (100%) rename tests/{test_lattice_mixed => regression_tests/lattice_mixed}/materials.xml (100%) rename tests/{test_lattice_mixed => regression_tests/lattice_mixed}/plots.xml (100%) rename tests/{test_lattice_mixed => regression_tests/lattice_mixed}/results_true.dat (100%) rename tests/{test_lattice_mixed => regression_tests/lattice_mixed}/settings.xml (100%) create mode 100644 tests/regression_tests/lattice_mixed/test.py rename tests/{test_lattice_multiple => regression_tests/lattice_multiple}/geometry.xml (100%) rename tests/{test_lattice_multiple => regression_tests/lattice_multiple}/materials.xml (100%) rename tests/{test_lattice_multiple => regression_tests/lattice_multiple}/results_true.dat (100%) rename tests/{test_lattice_multiple => regression_tests/lattice_multiple}/settings.xml (100%) create mode 100644 tests/regression_tests/lattice_multiple/test.py rename tests/{test_mg_basic => regression_tests/mg_basic}/inputs_true.dat (98%) rename tests/{test_mg_basic => regression_tests/mg_basic}/results_true.dat (100%) rename tests/{test_mg_basic/test_mg_basic.py => regression_tests/mg_basic/test.py} (82%) rename tests/{test_mg_convert => regression_tests/mg_convert}/inputs_true.dat (100%) rename tests/{test_mg_convert => regression_tests/mg_convert}/results_true.dat (100%) rename tests/{test_mg_convert/test_mg_convert.py => regression_tests/mg_convert/test.py} (99%) rename tests/{test_mg_legendre => regression_tests/mg_legendre}/inputs_true.dat (96%) rename tests/{test_mg_legendre => regression_tests/mg_legendre}/results_true.dat (100%) rename tests/{test_mg_legendre/test_mg_legendre.py => regression_tests/mg_legendre/test.py} (85%) rename tests/{test_mg_max_order => regression_tests/mg_max_order}/inputs_true.dat (96%) rename tests/{test_mg_max_order => regression_tests/mg_max_order}/results_true.dat (100%) rename tests/{test_mg_max_order/test_mg_max_order.py => regression_tests/mg_max_order/test.py} (84%) rename tests/{test_mg_nuclide => regression_tests/mg_nuclide}/inputs_true.dat (98%) rename tests/{test_mg_nuclide => regression_tests/mg_nuclide}/results_true.dat (100%) rename tests/{test_mg_nuclide/test_mg_nuclide.py => regression_tests/mg_nuclide/test.py} (82%) rename tests/{test_mg_survival_biasing => regression_tests/mg_survival_biasing}/inputs_true.dat (98%) rename tests/{test_mg_survival_biasing => regression_tests/mg_survival_biasing}/results_true.dat (100%) rename tests/{test_mg_survival_biasing/test_mg_survival_biasing.py => regression_tests/mg_survival_biasing/test.py} (84%) rename tests/{test_mg_tallies => regression_tests/mg_tallies}/inputs_true.dat (99%) rename tests/{test_mg_tallies => regression_tests/mg_tallies}/results_true.dat (100%) rename tests/{test_mg_tallies/test_mg_tallies.py => regression_tests/mg_tallies/test.py} (98%) rename tests/{test_mgxs_library_ce_to_mg => regression_tests/mgxs_library_ce_to_mg}/inputs_true.dat (100%) rename tests/{test_mgxs_library_ce_to_mg => regression_tests/mgxs_library_ce_to_mg}/results_true.dat (100%) rename tests/{test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py => regression_tests/mgxs_library_ce_to_mg/test.py} (98%) rename tests/{test_mgxs_library_condense => regression_tests/mgxs_library_condense}/inputs_true.dat (100%) rename tests/{test_mgxs_library_condense => regression_tests/mgxs_library_condense}/results_true.dat (100%) rename tests/{test_mgxs_library_condense/test_mgxs_library_condense.py => regression_tests/mgxs_library_condense/test.py} (97%) rename tests/{test_mgxs_library_distribcell => regression_tests/mgxs_library_distribcell}/inputs_true.dat (100%) rename tests/{test_mgxs_library_distribcell => regression_tests/mgxs_library_distribcell}/results_true.dat (100%) rename tests/{test_mgxs_library_distribcell/test_mgxs_library_distribcell.py => regression_tests/mgxs_library_distribcell/test.py} (97%) rename tests/{test_mgxs_library_hdf5 => regression_tests/mgxs_library_hdf5}/inputs_true.dat (100%) rename tests/{test_mgxs_library_hdf5 => regression_tests/mgxs_library_hdf5}/results_true.dat (100%) rename tests/{test_mgxs_library_hdf5/test_mgxs_library_hdf5.py => regression_tests/mgxs_library_hdf5/test.py} (98%) rename tests/{test_mgxs_library_mesh => regression_tests/mgxs_library_mesh}/inputs_true.dat (100%) rename tests/{test_mgxs_library_mesh => regression_tests/mgxs_library_mesh}/results_true.dat (100%) rename tests/{test_mgxs_library_mesh/test_mgxs_library_mesh.py => regression_tests/mgxs_library_mesh/test.py} (97%) rename tests/{test_mgxs_library_no_nuclides => regression_tests/mgxs_library_no_nuclides}/inputs_true.dat (100%) rename tests/{test_mgxs_library_no_nuclides => regression_tests/mgxs_library_no_nuclides}/results_true.dat (100%) rename tests/{test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py => regression_tests/mgxs_library_no_nuclides/test.py} (97%) rename tests/{test_mgxs_library_nuclides => regression_tests/mgxs_library_nuclides}/inputs_true.dat (100%) rename tests/{test_mgxs_library_nuclides => regression_tests/mgxs_library_nuclides}/results_true.dat (100%) rename tests/{test_mgxs_library_nuclides/test_mgxs_library_nuclides.py => regression_tests/mgxs_library_nuclides/test.py} (97%) rename tests/{test_multipole => regression_tests/multipole}/inputs_true.dat (100%) rename tests/{test_multipole => regression_tests/multipole}/results_true.dat (100%) rename tests/{test_multipole/test_multipole.py => regression_tests/multipole/test.py} (98%) rename tests/{test_output => regression_tests/output}/geometry.xml (100%) rename tests/{test_output => regression_tests/output}/materials.xml (100%) rename tests/{test_output => regression_tests/output}/results_true.dat (100%) rename tests/{test_output => regression_tests/output}/settings.xml (100%) rename tests/{test_output/test_output.py => regression_tests/output/test.py} (94%) rename tests/{test_particle_restart_eigval => regression_tests/particle_restart_eigval}/geometry.xml (100%) rename tests/{test_particle_restart_eigval => regression_tests/particle_restart_eigval}/materials.xml (100%) rename tests/{test_particle_restart_eigval => regression_tests/particle_restart_eigval}/results_true.dat (100%) rename tests/{test_particle_restart_eigval => regression_tests/particle_restart_eigval}/settings.xml (100%) rename tests/{test_particle_restart_eigval/test_particle_restart_eigval.py => regression_tests/particle_restart_eigval/test.py} (79%) rename tests/{test_particle_restart_fixed => regression_tests/particle_restart_fixed}/geometry.xml (100%) rename tests/{test_particle_restart_fixed => regression_tests/particle_restart_fixed}/materials.xml (100%) rename tests/{test_particle_restart_fixed => regression_tests/particle_restart_fixed}/results_true.dat (100%) rename tests/{test_particle_restart_fixed => regression_tests/particle_restart_fixed}/settings.xml (100%) rename tests/{test_particle_restart_fixed/test_particle_restart_fixed.py => regression_tests/particle_restart_fixed/test.py} (79%) rename tests/{test_periodic => regression_tests/periodic}/inputs_true.dat (100%) rename tests/{test_periodic => regression_tests/periodic}/results_true.dat (100%) rename tests/{test_periodic/test_periodic.py => regression_tests/periodic/test.py} (97%) rename tests/{test_plot => regression_tests/plot}/geometry.xml (100%) rename tests/{test_plot => regression_tests/plot}/materials.xml (100%) rename tests/{test_plot => regression_tests/plot}/plots.xml (100%) rename tests/{test_plot => regression_tests/plot}/results_true.dat (100%) rename tests/{test_plot => regression_tests/plot}/settings.xml (100%) rename tests/{test_plot/test_plot.py => regression_tests/plot/test.py} (97%) rename tests/{test_ptables_off => regression_tests/ptables_off}/geometry.xml (100%) rename tests/{test_ptables_off => regression_tests/ptables_off}/materials.xml (100%) rename tests/{test_ptables_off => regression_tests/ptables_off}/results_true.dat (100%) rename tests/{test_ptables_off => regression_tests/ptables_off}/settings.xml (100%) create mode 100644 tests/regression_tests/ptables_off/test.py rename tests/{test_quadric_surfaces => regression_tests/quadric_surfaces}/geometry.xml (100%) rename tests/{test_quadric_surfaces => regression_tests/quadric_surfaces}/materials.xml (100%) rename tests/{test_quadric_surfaces => regression_tests/quadric_surfaces}/results_true.dat (100%) rename tests/{test_quadric_surfaces => regression_tests/quadric_surfaces}/settings.xml (100%) create mode 100755 tests/regression_tests/quadric_surfaces/test.py rename tests/{test_reflective_plane => regression_tests/reflective_plane}/geometry.xml (100%) rename tests/{test_reflective_plane => regression_tests/reflective_plane}/materials.xml (100%) rename tests/{test_reflective_plane => regression_tests/reflective_plane}/results_true.dat (100%) rename tests/{test_reflective_plane => regression_tests/reflective_plane}/settings.xml (100%) create mode 100644 tests/regression_tests/reflective_plane/test.py rename tests/{test_resonance_scattering => regression_tests/resonance_scattering}/inputs_true.dat (100%) rename tests/{test_resonance_scattering => regression_tests/resonance_scattering}/results_true.dat (100%) rename tests/{test_resonance_scattering/test_resonance_scattering.py => regression_tests/resonance_scattering/test.py} (96%) rename tests/{test_rotation => regression_tests/rotation}/geometry.xml (100%) rename tests/{test_rotation => regression_tests/rotation}/materials.xml (100%) rename tests/{test_rotation => regression_tests/rotation}/results_true.dat (100%) rename tests/{test_rotation => regression_tests/rotation}/settings.xml (100%) create mode 100644 tests/regression_tests/rotation/test.py rename tests/{test_salphabeta => regression_tests/salphabeta}/inputs_true.dat (100%) rename tests/{test_salphabeta => regression_tests/salphabeta}/results_true.dat (100%) rename tests/{test_salphabeta/test_salphabeta.py => regression_tests/salphabeta/test.py} (97%) rename tests/{test_score_current => regression_tests/score_current}/geometry.xml (100%) rename tests/{test_score_current => regression_tests/score_current}/materials.xml (100%) rename tests/{test_score_current => regression_tests/score_current}/results_true.dat (100%) rename tests/{test_score_current => regression_tests/score_current}/settings.xml (100%) rename tests/{test_score_current => regression_tests/score_current}/tallies.xml (100%) rename tests/{test_score_current/test_score_current.py => regression_tests/score_current/test.py} (77%) rename tests/{test_seed => regression_tests/seed}/geometry.xml (100%) rename tests/{test_seed => regression_tests/seed}/materials.xml (100%) rename tests/{test_seed => regression_tests/seed}/results_true.dat (100%) rename tests/{test_seed => regression_tests/seed}/settings.xml (100%) create mode 100644 tests/regression_tests/seed/test.py rename tests/{test_source => regression_tests/source}/inputs_true.dat (100%) rename tests/{test_source => regression_tests/source}/results_true.dat (100%) rename tests/{test_source/test_source.py => regression_tests/source/test.py} (97%) rename tests/{test_source_file => regression_tests/source_file}/geometry.xml (100%) rename tests/{test_source_file => regression_tests/source_file}/materials.xml (100%) rename tests/{test_source_file => regression_tests/source_file}/results_true.dat (100%) rename tests/{test_source_file => regression_tests/source_file}/settings.xml (100%) rename tests/{test_source_file/test_source_file.py => regression_tests/source_file/test.py} (98%) rename tests/{test_sourcepoint_batch => regression_tests/sourcepoint_batch}/geometry.xml (100%) rename tests/{test_sourcepoint_batch => regression_tests/sourcepoint_batch}/materials.xml (100%) rename tests/{test_sourcepoint_batch => regression_tests/sourcepoint_batch}/results_true.dat (100%) rename tests/{test_sourcepoint_batch => regression_tests/sourcepoint_batch}/settings.xml (100%) rename tests/{test_sourcepoint_batch/test_sourcepoint_batch.py => regression_tests/sourcepoint_batch/test.py} (95%) rename tests/{test_sourcepoint_latest => regression_tests/sourcepoint_latest}/geometry.xml (100%) rename tests/{test_sourcepoint_latest => regression_tests/sourcepoint_latest}/materials.xml (100%) rename tests/{test_sourcepoint_latest => regression_tests/sourcepoint_latest}/results_true.dat (100%) rename tests/{test_sourcepoint_latest => regression_tests/sourcepoint_latest}/settings.xml (100%) rename tests/{test_sourcepoint_latest/test_sourcepoint_latest.py => regression_tests/sourcepoint_latest/test.py} (91%) rename tests/{test_sourcepoint_restart => regression_tests/sourcepoint_restart}/geometry.xml (100%) rename tests/{test_sourcepoint_restart => regression_tests/sourcepoint_restart}/materials.xml (100%) rename tests/{test_sourcepoint_restart => regression_tests/sourcepoint_restart}/results_true.dat (100%) rename tests/{test_sourcepoint_restart => regression_tests/sourcepoint_restart}/settings.xml (100%) rename tests/{test_sourcepoint_restart => regression_tests/sourcepoint_restart}/tallies.xml (100%) create mode 100644 tests/regression_tests/sourcepoint_restart/test.py rename tests/{test_statepoint_batch => regression_tests/statepoint_batch}/geometry.xml (100%) rename tests/{test_statepoint_batch => regression_tests/statepoint_batch}/materials.xml (100%) rename tests/{test_statepoint_batch => regression_tests/statepoint_batch}/results_true.dat (100%) rename tests/{test_statepoint_batch => regression_tests/statepoint_batch}/settings.xml (100%) rename tests/{test_statepoint_batch/test_statepoint_batch.py => regression_tests/statepoint_batch/test.py} (91%) rename tests/{test_statepoint_restart => regression_tests/statepoint_restart}/geometry.xml (100%) rename tests/{test_statepoint_restart => regression_tests/statepoint_restart}/materials.xml (100%) rename tests/{test_statepoint_restart => regression_tests/statepoint_restart}/results_true.dat (100%) rename tests/{test_statepoint_restart => regression_tests/statepoint_restart}/settings.xml (100%) rename tests/{test_statepoint_restart => regression_tests/statepoint_restart}/tallies.xml (100%) rename tests/{test_statepoint_restart/test_statepoint_restart.py => regression_tests/statepoint_restart/test.py} (97%) rename tests/{test_statepoint_sourcesep => regression_tests/statepoint_sourcesep}/geometry.xml (100%) rename tests/{test_statepoint_sourcesep => regression_tests/statepoint_sourcesep}/materials.xml (100%) rename tests/{test_statepoint_sourcesep => regression_tests/statepoint_sourcesep}/results_true.dat (100%) rename tests/{test_statepoint_sourcesep => regression_tests/statepoint_sourcesep}/settings.xml (100%) rename tests/{test_statepoint_sourcesep/test_statepoint_sourcesep.py => regression_tests/statepoint_sourcesep/test.py} (94%) rename tests/{test_surface_tally => regression_tests/surface_tally}/inputs_true.dat (100%) rename tests/{test_surface_tally => regression_tests/surface_tally}/results_true.dat (100%) rename tests/{test_surface_tally/test_surface_tally.py => regression_tests/surface_tally/test.py} (99%) rename tests/{test_survival_biasing => regression_tests/survival_biasing}/geometry.xml (100%) rename tests/{test_survival_biasing => regression_tests/survival_biasing}/materials.xml (100%) rename tests/{test_survival_biasing => regression_tests/survival_biasing}/results_true.dat (100%) rename tests/{test_survival_biasing => regression_tests/survival_biasing}/settings.xml (100%) rename tests/{test_survival_biasing => regression_tests/survival_biasing}/tallies.xml (100%) create mode 100644 tests/regression_tests/survival_biasing/test.py rename tests/{test_tallies => regression_tests/tallies}/inputs_true.dat (100%) rename tests/{test_tallies => regression_tests/tallies}/results_true.dat (100%) rename tests/{test_tallies/test_tallies.py => regression_tests/tallies/test.py} (99%) rename tests/{test_tally_aggregation => regression_tests/tally_aggregation}/inputs_true.dat (100%) rename tests/{test_tally_aggregation => regression_tests/tally_aggregation}/results_true.dat (100%) rename tests/{test_tally_aggregation/test_tally_aggregation.py => regression_tests/tally_aggregation/test.py} (97%) rename tests/{test_tally_arithmetic => regression_tests/tally_arithmetic}/inputs_true.dat (100%) rename tests/{test_tally_arithmetic => regression_tests/tally_arithmetic}/results_true.dat (100%) rename tests/{test_tally_arithmetic/test_tally_arithmetic.py => regression_tests/tally_arithmetic/test.py} (98%) rename tests/{test_tally_assumesep => regression_tests/tally_assumesep}/geometry.xml (100%) rename tests/{test_tally_assumesep => regression_tests/tally_assumesep}/materials.xml (100%) rename tests/{test_tally_assumesep => regression_tests/tally_assumesep}/results_true.dat (100%) rename tests/{test_tally_assumesep => regression_tests/tally_assumesep}/settings.xml (100%) rename tests/{test_tally_assumesep => regression_tests/tally_assumesep}/tallies.xml (100%) create mode 100644 tests/regression_tests/tally_assumesep/test.py rename tests/{test_tally_nuclides => regression_tests/tally_nuclides}/geometry.xml (100%) rename tests/{test_tally_nuclides => regression_tests/tally_nuclides}/materials.xml (100%) rename tests/{test_tally_nuclides => regression_tests/tally_nuclides}/results_true.dat (100%) rename tests/{test_tally_nuclides => regression_tests/tally_nuclides}/settings.xml (100%) rename tests/{test_tally_nuclides => regression_tests/tally_nuclides}/tallies.xml (100%) create mode 100644 tests/regression_tests/tally_nuclides/test.py rename tests/{test_tally_slice_merge => regression_tests/tally_slice_merge}/inputs_true.dat (100%) rename tests/{test_tally_slice_merge => regression_tests/tally_slice_merge}/results_true.dat (100%) rename tests/{test_tally_slice_merge/test_tally_slice_merge.py => regression_tests/tally_slice_merge/test.py} (99%) rename tests/{test_trace => regression_tests/trace}/geometry.xml (100%) rename tests/{test_trace => regression_tests/trace}/materials.xml (100%) rename tests/{test_trace => regression_tests/trace}/results_true.dat (100%) rename tests/{test_trace => regression_tests/trace}/settings.xml (100%) create mode 100644 tests/regression_tests/trace/test.py rename tests/{test_track_output => regression_tests/track_output}/geometry.xml (100%) rename tests/{test_track_output => regression_tests/track_output}/materials.xml (100%) rename tests/{test_track_output => regression_tests/track_output}/results_true.dat (100%) rename tests/{test_track_output => regression_tests/track_output}/settings.xml (100%) rename tests/{test_track_output/test_track_output.py => regression_tests/track_output/test.py} (96%) rename tests/{test_translation => regression_tests/translation}/geometry.xml (100%) rename tests/{test_translation => regression_tests/translation}/materials.xml (100%) rename tests/{test_translation => regression_tests/translation}/results_true.dat (100%) rename tests/{test_translation => regression_tests/translation}/settings.xml (100%) create mode 100644 tests/regression_tests/translation/test.py rename tests/{test_trigger_batch_interval => regression_tests/trigger_batch_interval}/geometry.xml (100%) rename tests/{test_trigger_batch_interval => regression_tests/trigger_batch_interval}/materials.xml (100%) rename tests/{test_trigger_batch_interval => regression_tests/trigger_batch_interval}/results_true.dat (100%) rename tests/{test_trigger_batch_interval => regression_tests/trigger_batch_interval}/settings.xml (100%) rename tests/{test_trigger_batch_interval => regression_tests/trigger_batch_interval}/tallies.xml (100%) rename tests/{test_trigger_batch_interval/test_trigger_batch_interval.py => regression_tests/trigger_batch_interval/test.py} (76%) rename tests/{test_trigger_no_batch_interval => regression_tests/trigger_no_batch_interval}/geometry.xml (100%) rename tests/{test_trigger_no_batch_interval => regression_tests/trigger_no_batch_interval}/materials.xml (100%) rename tests/{test_trigger_no_batch_interval => regression_tests/trigger_no_batch_interval}/results_true.dat (100%) rename tests/{test_trigger_no_batch_interval => regression_tests/trigger_no_batch_interval}/settings.xml (100%) rename tests/{test_trigger_no_batch_interval => regression_tests/trigger_no_batch_interval}/tallies.xml (100%) rename tests/{test_trigger_no_batch_interval/test_trigger_no_batch_interval.py => regression_tests/trigger_no_batch_interval/test.py} (76%) rename tests/{test_trigger_no_status => regression_tests/trigger_no_status}/geometry.xml (100%) rename tests/{test_trigger_no_status => regression_tests/trigger_no_status}/materials.xml (100%) rename tests/{test_trigger_no_status => regression_tests/trigger_no_status}/results_true.dat (100%) rename tests/{test_trigger_no_status => regression_tests/trigger_no_status}/settings.xml (100%) rename tests/{test_trigger_no_status => regression_tests/trigger_no_status}/tallies.xml (100%) create mode 100644 tests/regression_tests/trigger_no_status/test.py rename tests/{test_trigger_tallies => regression_tests/trigger_tallies}/geometry.xml (100%) rename tests/{test_trigger_tallies => regression_tests/trigger_tallies}/materials.xml (100%) rename tests/{test_trigger_tallies => regression_tests/trigger_tallies}/results_true.dat (100%) rename tests/{test_trigger_tallies => regression_tests/trigger_tallies}/settings.xml (100%) rename tests/{test_trigger_tallies => regression_tests/trigger_tallies}/tallies.xml (100%) rename tests/{test_trigger_tallies/test_trigger_tallies.py => regression_tests/trigger_tallies/test.py} (76%) rename tests/{test_triso => regression_tests/triso}/inputs_true.dat (100%) rename tests/{test_triso => regression_tests/triso}/results_true.dat (100%) rename tests/{test_triso/test_triso.py => regression_tests/triso/test.py} (98%) rename tests/{test_uniform_fs => regression_tests/uniform_fs}/geometry.xml (100%) rename tests/{test_uniform_fs => regression_tests/uniform_fs}/materials.xml (100%) rename tests/{test_uniform_fs => regression_tests/uniform_fs}/results_true.dat (100%) rename tests/{test_uniform_fs => regression_tests/uniform_fs}/settings.xml (100%) create mode 100644 tests/regression_tests/uniform_fs/test.py rename tests/{test_universe => regression_tests/universe}/geometry.xml (100%) rename tests/{test_universe => regression_tests/universe}/materials.xml (100%) rename tests/{test_universe => regression_tests/universe}/results_true.dat (100%) rename tests/{test_universe => regression_tests/universe}/settings.xml (100%) create mode 100644 tests/regression_tests/universe/test.py rename tests/{test_void => regression_tests/void}/geometry.xml (100%) rename tests/{test_void => regression_tests/void}/materials.xml (100%) rename tests/{test_void => regression_tests/void}/results_true.dat (100%) rename tests/{test_void => regression_tests/void}/settings.xml (100%) create mode 100644 tests/regression_tests/void/test.py rename tests/{test_volume_calc => regression_tests/volume_calc}/inputs_true.dat (100%) rename tests/{test_volume_calc => regression_tests/volume_calc}/results_true.dat (100%) rename tests/{test_volume_calc/test_volume_calc.py => regression_tests/volume_calc/test.py} (98%) delete mode 100755 tests/test_complex_cell/test_complex_cell.py delete mode 100644 tests/test_infinite_cell/test_infinite_cell.py delete mode 100644 tests/test_lattice/test_lattice.py delete mode 100644 tests/test_lattice_hex/test_lattice_hex.py delete mode 100644 tests/test_lattice_mixed/test_lattice_mixed.py delete mode 100644 tests/test_lattice_multiple/test_lattice_multiple.py delete mode 100644 tests/test_ptables_off/test_ptables_off.py delete mode 100755 tests/test_quadric_surfaces/test_quadric_surfaces.py delete mode 100644 tests/test_reflective_plane/test_reflective_plane.py delete mode 100644 tests/test_rotation/test_rotation.py delete mode 100644 tests/test_seed/test_seed.py delete mode 100644 tests/test_sourcepoint_restart/test_sourcepoint_restart.py delete mode 100644 tests/test_survival_biasing/test_survival_biasing.py delete mode 100644 tests/test_tally_assumesep/test_tally_assumesep.py delete mode 100644 tests/test_tally_nuclides/test_tally_nuclides.py delete mode 100644 tests/test_trace/test_trace.py delete mode 100644 tests/test_translation/test_translation.py delete mode 100644 tests/test_trigger_no_status/test_trigger_no_status.py delete mode 100644 tests/test_uniform_fs/test_uniform_fs.py delete mode 100644 tests/test_universe/test_universe.py delete mode 100644 tests/test_void/test_void.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cb4f9bb3d7..5d0fcb0ab3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -531,7 +531,7 @@ endif() include(CTest) # Get a list of all the tests to run -file(GLOB_RECURSE TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_*.py) +file(GLOB_RECURSE TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test.py) # Loop through all the tests foreach(test ${TESTS}) @@ -552,20 +552,20 @@ foreach(test ${TESTS}) endif() # Add serial test - add_test(NAME ${TEST_NAME} + add_test(NAME ${TEST_PATH} WORKING_DIRECTORY ${TEST_PATH} COMMAND $) else() # Check serial/parallel if (${MPI_ENABLED}) # Preform a parallel test - add_test(NAME ${TEST_NAME} + add_test(NAME ${TEST_PATH} WORKING_DIRECTORY ${TEST_PATH} COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $ --mpi_exec ${MPI_DIR}/mpiexec) else() # Perform a serial test - add_test(NAME ${TEST_NAME} + add_test(NAME ${TEST_PATH} WORKING_DIRECTORY ${TEST_PATH} COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $) endif() diff --git a/openmc/examples.py b/openmc/examples.py index 3d6a068273..d48d26839f 100644 --- a/openmc/examples.py +++ b/openmc/examples.py @@ -587,7 +587,7 @@ def slab_mg(reps=None, as_macro=True): # Define the materials file model.xs_data = xs - model.materials.cross_sections = "../1d_mgxs.h5" + model.materials.cross_sections = "../../1d_mgxs.h5" # Define surfaces. # Assembly/Problem Boundary diff --git a/tests/test_asymmetric_lattice/inputs_true.dat b/tests/regression_tests/asymmetric_lattice/inputs_true.dat similarity index 100% rename from tests/test_asymmetric_lattice/inputs_true.dat rename to tests/regression_tests/asymmetric_lattice/inputs_true.dat diff --git a/tests/test_asymmetric_lattice/results_true.dat b/tests/regression_tests/asymmetric_lattice/results_true.dat similarity index 100% rename from tests/test_asymmetric_lattice/results_true.dat rename to tests/regression_tests/asymmetric_lattice/results_true.dat diff --git a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py b/tests/regression_tests/asymmetric_lattice/test.py similarity index 98% rename from tests/test_asymmetric_lattice/test_asymmetric_lattice.py rename to tests/regression_tests/asymmetric_lattice/test.py index 58c1b22ab5..f7cbf35c62 100644 --- a/tests/test_asymmetric_lattice/test_asymmetric_lattice.py +++ b/tests/regression_tests/asymmetric_lattice/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_cmfd_feed/cmfd.xml b/tests/regression_tests/cmfd_feed/cmfd.xml similarity index 100% rename from tests/test_cmfd_feed/cmfd.xml rename to tests/regression_tests/cmfd_feed/cmfd.xml diff --git a/tests/test_cmfd_feed/geometry.xml b/tests/regression_tests/cmfd_feed/geometry.xml similarity index 100% rename from tests/test_cmfd_feed/geometry.xml rename to tests/regression_tests/cmfd_feed/geometry.xml diff --git a/tests/test_cmfd_feed/materials.xml b/tests/regression_tests/cmfd_feed/materials.xml similarity index 100% rename from tests/test_cmfd_feed/materials.xml rename to tests/regression_tests/cmfd_feed/materials.xml diff --git a/tests/test_cmfd_feed/results_true.dat b/tests/regression_tests/cmfd_feed/results_true.dat similarity index 100% rename from tests/test_cmfd_feed/results_true.dat rename to tests/regression_tests/cmfd_feed/results_true.dat diff --git a/tests/test_cmfd_feed/settings.xml b/tests/regression_tests/cmfd_feed/settings.xml similarity index 100% rename from tests/test_cmfd_feed/settings.xml rename to tests/regression_tests/cmfd_feed/settings.xml diff --git a/tests/test_cmfd_feed/tallies.xml b/tests/regression_tests/cmfd_feed/tallies.xml similarity index 100% rename from tests/test_cmfd_feed/tallies.xml rename to tests/regression_tests/cmfd_feed/tallies.xml diff --git a/tests/test_cmfd_feed/test_cmfd_feed.py b/tests/regression_tests/cmfd_feed/test.py similarity index 77% rename from tests/test_cmfd_feed/test_cmfd_feed.py rename to tests/regression_tests/cmfd_feed/test.py index 17bebf68c0..30e61d03f5 100644 --- a/tests/test_cmfd_feed/test_cmfd_feed.py +++ b/tests/regression_tests/cmfd_feed/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import CMFDTestHarness diff --git a/tests/test_cmfd_nofeed/cmfd.xml b/tests/regression_tests/cmfd_nofeed/cmfd.xml similarity index 100% rename from tests/test_cmfd_nofeed/cmfd.xml rename to tests/regression_tests/cmfd_nofeed/cmfd.xml diff --git a/tests/test_cmfd_nofeed/geometry.xml b/tests/regression_tests/cmfd_nofeed/geometry.xml similarity index 100% rename from tests/test_cmfd_nofeed/geometry.xml rename to tests/regression_tests/cmfd_nofeed/geometry.xml diff --git a/tests/test_cmfd_nofeed/materials.xml b/tests/regression_tests/cmfd_nofeed/materials.xml similarity index 100% rename from tests/test_cmfd_nofeed/materials.xml rename to tests/regression_tests/cmfd_nofeed/materials.xml diff --git a/tests/test_cmfd_nofeed/results_true.dat b/tests/regression_tests/cmfd_nofeed/results_true.dat similarity index 100% rename from tests/test_cmfd_nofeed/results_true.dat rename to tests/regression_tests/cmfd_nofeed/results_true.dat diff --git a/tests/test_cmfd_nofeed/settings.xml b/tests/regression_tests/cmfd_nofeed/settings.xml similarity index 100% rename from tests/test_cmfd_nofeed/settings.xml rename to tests/regression_tests/cmfd_nofeed/settings.xml diff --git a/tests/test_cmfd_nofeed/tallies.xml b/tests/regression_tests/cmfd_nofeed/tallies.xml similarity index 100% rename from tests/test_cmfd_nofeed/tallies.xml rename to tests/regression_tests/cmfd_nofeed/tallies.xml diff --git a/tests/test_cmfd_nofeed/test_cmfd_nofeed.py b/tests/regression_tests/cmfd_nofeed/test.py similarity index 77% rename from tests/test_cmfd_nofeed/test_cmfd_nofeed.py rename to tests/regression_tests/cmfd_nofeed/test.py index 17bebf68c0..30e61d03f5 100644 --- a/tests/test_cmfd_nofeed/test_cmfd_nofeed.py +++ b/tests/regression_tests/cmfd_nofeed/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import CMFDTestHarness diff --git a/tests/test_complex_cell/geometry.xml b/tests/regression_tests/complex_cell/geometry.xml similarity index 100% rename from tests/test_complex_cell/geometry.xml rename to tests/regression_tests/complex_cell/geometry.xml diff --git a/tests/test_complex_cell/materials.xml b/tests/regression_tests/complex_cell/materials.xml similarity index 100% rename from tests/test_complex_cell/materials.xml rename to tests/regression_tests/complex_cell/materials.xml diff --git a/tests/test_complex_cell/results_true.dat b/tests/regression_tests/complex_cell/results_true.dat similarity index 100% rename from tests/test_complex_cell/results_true.dat rename to tests/regression_tests/complex_cell/results_true.dat diff --git a/tests/test_complex_cell/settings.xml b/tests/regression_tests/complex_cell/settings.xml similarity index 100% rename from tests/test_complex_cell/settings.xml rename to tests/regression_tests/complex_cell/settings.xml diff --git a/tests/test_complex_cell/tallies.xml b/tests/regression_tests/complex_cell/tallies.xml similarity index 100% rename from tests/test_complex_cell/tallies.xml rename to tests/regression_tests/complex_cell/tallies.xml diff --git a/tests/test_confidence_intervals/test_confidence_intervals.py b/tests/regression_tests/complex_cell/test.py similarity index 76% rename from tests/test_confidence_intervals/test_confidence_intervals.py rename to tests/regression_tests/complex_cell/test.py index b04fcc6eba..43f8e5ff0f 100755 --- a/tests/test_confidence_intervals/test_confidence_intervals.py +++ b/tests/regression_tests/complex_cell/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_confidence_intervals/geometry.xml b/tests/regression_tests/confidence_intervals/geometry.xml similarity index 100% rename from tests/test_confidence_intervals/geometry.xml rename to tests/regression_tests/confidence_intervals/geometry.xml diff --git a/tests/test_confidence_intervals/materials.xml b/tests/regression_tests/confidence_intervals/materials.xml similarity index 100% rename from tests/test_confidence_intervals/materials.xml rename to tests/regression_tests/confidence_intervals/materials.xml diff --git a/tests/test_confidence_intervals/results_true.dat b/tests/regression_tests/confidence_intervals/results_true.dat similarity index 100% rename from tests/test_confidence_intervals/results_true.dat rename to tests/regression_tests/confidence_intervals/results_true.dat diff --git a/tests/test_confidence_intervals/settings.xml b/tests/regression_tests/confidence_intervals/settings.xml similarity index 100% rename from tests/test_confidence_intervals/settings.xml rename to tests/regression_tests/confidence_intervals/settings.xml diff --git a/tests/test_confidence_intervals/tallies.xml b/tests/regression_tests/confidence_intervals/tallies.xml similarity index 100% rename from tests/test_confidence_intervals/tallies.xml rename to tests/regression_tests/confidence_intervals/tallies.xml diff --git a/tests/test_density/test_density.py b/tests/regression_tests/confidence_intervals/test.py old mode 100644 new mode 100755 similarity index 76% rename from tests/test_density/test_density.py rename to tests/regression_tests/confidence_intervals/test.py index b04fcc6eba..43f8e5ff0f --- a/tests/test_density/test_density.py +++ b/tests/regression_tests/confidence_intervals/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_create_fission_neutrons/inputs_true.dat b/tests/regression_tests/create_fission_neutrons/inputs_true.dat similarity index 100% rename from tests/test_create_fission_neutrons/inputs_true.dat rename to tests/regression_tests/create_fission_neutrons/inputs_true.dat diff --git a/tests/test_create_fission_neutrons/results_true.dat b/tests/regression_tests/create_fission_neutrons/results_true.dat similarity index 100% rename from tests/test_create_fission_neutrons/results_true.dat rename to tests/regression_tests/create_fission_neutrons/results_true.dat diff --git a/tests/test_create_fission_neutrons/test_create_fission_neutrons.py b/tests/regression_tests/create_fission_neutrons/test.py similarity index 97% rename from tests/test_create_fission_neutrons/test_create_fission_neutrons.py rename to tests/regression_tests/create_fission_neutrons/test.py index 87abeda7fe..080a0ab0d8 100755 --- a/tests/test_create_fission_neutrons/test_create_fission_neutrons.py +++ b/tests/regression_tests/create_fission_neutrons/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_density/geometry.xml b/tests/regression_tests/density/geometry.xml similarity index 100% rename from tests/test_density/geometry.xml rename to tests/regression_tests/density/geometry.xml diff --git a/tests/test_density/materials.xml b/tests/regression_tests/density/materials.xml similarity index 100% rename from tests/test_density/materials.xml rename to tests/regression_tests/density/materials.xml diff --git a/tests/test_density/results_true.dat b/tests/regression_tests/density/results_true.dat similarity index 100% rename from tests/test_density/results_true.dat rename to tests/regression_tests/density/results_true.dat diff --git a/tests/test_density/settings.xml b/tests/regression_tests/density/settings.xml similarity index 100% rename from tests/test_density/settings.xml rename to tests/regression_tests/density/settings.xml diff --git a/tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py b/tests/regression_tests/density/test.py similarity index 76% rename from tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py rename to tests/regression_tests/density/test.py index b04fcc6eba..43f8e5ff0f 100644 --- a/tests/test_eigenvalue_no_inactive/test_eigenvalue_no_inactive.py +++ b/tests/regression_tests/density/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_diff_tally/inputs_true.dat b/tests/regression_tests/diff_tally/inputs_true.dat similarity index 100% rename from tests/test_diff_tally/inputs_true.dat rename to tests/regression_tests/diff_tally/inputs_true.dat diff --git a/tests/test_diff_tally/results_true.dat b/tests/regression_tests/diff_tally/results_true.dat similarity index 100% rename from tests/test_diff_tally/results_true.dat rename to tests/regression_tests/diff_tally/results_true.dat diff --git a/tests/test_diff_tally/test_diff_tally.py b/tests/regression_tests/diff_tally/test.py similarity index 98% rename from tests/test_diff_tally/test_diff_tally.py rename to tests/regression_tests/diff_tally/test.py index 02798e70e0..5f1da9c30a 100644 --- a/tests/test_diff_tally/test_diff_tally.py +++ b/tests/regression_tests/diff_tally/test.py @@ -6,7 +6,7 @@ import sys import pandas as pd -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_distribmat/inputs_true.dat b/tests/regression_tests/distribmat/inputs_true.dat similarity index 100% rename from tests/test_distribmat/inputs_true.dat rename to tests/regression_tests/distribmat/inputs_true.dat diff --git a/tests/test_distribmat/results_true.dat b/tests/regression_tests/distribmat/results_true.dat similarity index 100% rename from tests/test_distribmat/results_true.dat rename to tests/regression_tests/distribmat/results_true.dat diff --git a/tests/test_distribmat/test_distribmat.py b/tests/regression_tests/distribmat/test.py similarity index 98% rename from tests/test_distribmat/test_distribmat.py rename to tests/regression_tests/distribmat/test.py index 9dd5d319a2..d18bb15430 100644 --- a/tests/test_distribmat/test_distribmat.py +++ b/tests/regression_tests/distribmat/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness, PyAPITestHarness import openmc diff --git a/tests/test_eigenvalue_genperbatch/geometry.xml b/tests/regression_tests/eigenvalue_genperbatch/geometry.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/geometry.xml rename to tests/regression_tests/eigenvalue_genperbatch/geometry.xml diff --git a/tests/test_eigenvalue_genperbatch/materials.xml b/tests/regression_tests/eigenvalue_genperbatch/materials.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/materials.xml rename to tests/regression_tests/eigenvalue_genperbatch/materials.xml diff --git a/tests/test_eigenvalue_genperbatch/results_true.dat b/tests/regression_tests/eigenvalue_genperbatch/results_true.dat similarity index 100% rename from tests/test_eigenvalue_genperbatch/results_true.dat rename to tests/regression_tests/eigenvalue_genperbatch/results_true.dat diff --git a/tests/test_eigenvalue_genperbatch/settings.xml b/tests/regression_tests/eigenvalue_genperbatch/settings.xml similarity index 100% rename from tests/test_eigenvalue_genperbatch/settings.xml rename to tests/regression_tests/eigenvalue_genperbatch/settings.xml diff --git a/tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py b/tests/regression_tests/eigenvalue_genperbatch/test.py similarity index 76% rename from tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py rename to tests/regression_tests/eigenvalue_genperbatch/test.py index 59a60b63a4..a36c2ae374 100644 --- a/tests/test_eigenvalue_genperbatch/test_eigenvalue_genperbatch.py +++ b/tests/regression_tests/eigenvalue_genperbatch/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_eigenvalue_no_inactive/geometry.xml b/tests/regression_tests/eigenvalue_no_inactive/geometry.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/geometry.xml rename to tests/regression_tests/eigenvalue_no_inactive/geometry.xml diff --git a/tests/test_eigenvalue_no_inactive/materials.xml b/tests/regression_tests/eigenvalue_no_inactive/materials.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/materials.xml rename to tests/regression_tests/eigenvalue_no_inactive/materials.xml diff --git a/tests/test_eigenvalue_no_inactive/results_true.dat b/tests/regression_tests/eigenvalue_no_inactive/results_true.dat similarity index 100% rename from tests/test_eigenvalue_no_inactive/results_true.dat rename to tests/regression_tests/eigenvalue_no_inactive/results_true.dat diff --git a/tests/test_eigenvalue_no_inactive/settings.xml b/tests/regression_tests/eigenvalue_no_inactive/settings.xml similarity index 100% rename from tests/test_eigenvalue_no_inactive/settings.xml rename to tests/regression_tests/eigenvalue_no_inactive/settings.xml diff --git a/tests/test_energy_grid/test_energy_grid.py b/tests/regression_tests/eigenvalue_no_inactive/test.py similarity index 76% rename from tests/test_energy_grid/test_energy_grid.py rename to tests/regression_tests/eigenvalue_no_inactive/test.py index b04fcc6eba..43f8e5ff0f 100644 --- a/tests/test_energy_grid/test_energy_grid.py +++ b/tests/regression_tests/eigenvalue_no_inactive/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_energy_cutoff/inputs_true.dat b/tests/regression_tests/energy_cutoff/inputs_true.dat similarity index 100% rename from tests/test_energy_cutoff/inputs_true.dat rename to tests/regression_tests/energy_cutoff/inputs_true.dat diff --git a/tests/test_energy_cutoff/results_true.dat b/tests/regression_tests/energy_cutoff/results_true.dat similarity index 100% rename from tests/test_energy_cutoff/results_true.dat rename to tests/regression_tests/energy_cutoff/results_true.dat diff --git a/tests/test_energy_cutoff/test_energy_cutoff.py b/tests/regression_tests/energy_cutoff/test.py similarity index 97% rename from tests/test_energy_cutoff/test_energy_cutoff.py rename to tests/regression_tests/energy_cutoff/test.py index 3aa3400c7a..74f7b2ab2a 100755 --- a/tests/test_energy_cutoff/test_energy_cutoff.py +++ b/tests/regression_tests/energy_cutoff/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_energy_grid/geometry.xml b/tests/regression_tests/energy_grid/geometry.xml similarity index 100% rename from tests/test_energy_grid/geometry.xml rename to tests/regression_tests/energy_grid/geometry.xml diff --git a/tests/test_energy_grid/materials.xml b/tests/regression_tests/energy_grid/materials.xml similarity index 100% rename from tests/test_energy_grid/materials.xml rename to tests/regression_tests/energy_grid/materials.xml diff --git a/tests/test_energy_grid/results_true.dat b/tests/regression_tests/energy_grid/results_true.dat similarity index 100% rename from tests/test_energy_grid/results_true.dat rename to tests/regression_tests/energy_grid/results_true.dat diff --git a/tests/test_energy_grid/settings.xml b/tests/regression_tests/energy_grid/settings.xml similarity index 100% rename from tests/test_energy_grid/settings.xml rename to tests/regression_tests/energy_grid/settings.xml diff --git a/tests/regression_tests/energy_grid/test.py b/tests/regression_tests/energy_grid/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/energy_grid/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_energy_laws/geometry.xml b/tests/regression_tests/energy_laws/geometry.xml similarity index 100% rename from tests/test_energy_laws/geometry.xml rename to tests/regression_tests/energy_laws/geometry.xml diff --git a/tests/test_energy_laws/materials.xml b/tests/regression_tests/energy_laws/materials.xml similarity index 100% rename from tests/test_energy_laws/materials.xml rename to tests/regression_tests/energy_laws/materials.xml diff --git a/tests/test_energy_laws/results_true.dat b/tests/regression_tests/energy_laws/results_true.dat similarity index 100% rename from tests/test_energy_laws/results_true.dat rename to tests/regression_tests/energy_laws/results_true.dat diff --git a/tests/test_energy_laws/settings.xml b/tests/regression_tests/energy_laws/settings.xml similarity index 100% rename from tests/test_energy_laws/settings.xml rename to tests/regression_tests/energy_laws/settings.xml diff --git a/tests/test_energy_laws/test_energy_laws.py b/tests/regression_tests/energy_laws/test.py similarity index 93% rename from tests/test_energy_laws/test_energy_laws.py rename to tests/regression_tests/energy_laws/test.py index 254126ff30..5180344dab 100644 --- a/tests/test_energy_laws/test_energy_laws.py +++ b/tests/regression_tests/energy_laws/test.py @@ -21,7 +21,7 @@ that use linear-linear interpolation. import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_enrichment/test_enrichment.py b/tests/regression_tests/enrichment/test.py similarity index 97% rename from tests/test_enrichment/test_enrichment.py rename to tests/regression_tests/enrichment/test.py index fa65d6dce0..395fafdf56 100644 --- a/tests/test_enrichment/test_enrichment.py +++ b/tests/regression_tests/enrichment/test.py @@ -5,7 +5,6 @@ import sys import numpy as np -sys.path.insert(0, os.pardir) sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from openmc import Material from openmc.data import NATURAL_ABUNDANCE, atomic_mass diff --git a/tests/test_entropy/geometry.xml b/tests/regression_tests/entropy/geometry.xml similarity index 100% rename from tests/test_entropy/geometry.xml rename to tests/regression_tests/entropy/geometry.xml diff --git a/tests/test_entropy/materials.xml b/tests/regression_tests/entropy/materials.xml similarity index 100% rename from tests/test_entropy/materials.xml rename to tests/regression_tests/entropy/materials.xml diff --git a/tests/test_entropy/results_true.dat b/tests/regression_tests/entropy/results_true.dat similarity index 100% rename from tests/test_entropy/results_true.dat rename to tests/regression_tests/entropy/results_true.dat diff --git a/tests/test_entropy/settings.xml b/tests/regression_tests/entropy/settings.xml similarity index 100% rename from tests/test_entropy/settings.xml rename to tests/regression_tests/entropy/settings.xml diff --git a/tests/test_entropy/test_entropy.py b/tests/regression_tests/entropy/test.py similarity index 94% rename from tests/test_entropy/test_entropy.py rename to tests/regression_tests/entropy/test.py index 36e2170af8..bbc6c0c7f4 100644 --- a/tests/test_entropy/test_entropy.py +++ b/tests/regression_tests/entropy/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness from openmc import StatePoint diff --git a/tests/test_filter_distribcell/case-1/geometry.xml b/tests/regression_tests/filter_distribcell/case-1/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/geometry.xml rename to tests/regression_tests/filter_distribcell/case-1/geometry.xml diff --git a/tests/test_filter_distribcell/case-1/materials.xml b/tests/regression_tests/filter_distribcell/case-1/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/materials.xml rename to tests/regression_tests/filter_distribcell/case-1/materials.xml diff --git a/tests/test_filter_distribcell/case-1/results_true.dat b/tests/regression_tests/filter_distribcell/case-1/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-1/results_true.dat rename to tests/regression_tests/filter_distribcell/case-1/results_true.dat diff --git a/tests/test_filter_distribcell/case-1/settings.xml b/tests/regression_tests/filter_distribcell/case-1/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/settings.xml rename to tests/regression_tests/filter_distribcell/case-1/settings.xml diff --git a/tests/test_filter_distribcell/case-1/tallies.xml b/tests/regression_tests/filter_distribcell/case-1/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-1/tallies.xml rename to tests/regression_tests/filter_distribcell/case-1/tallies.xml diff --git a/tests/test_filter_distribcell/case-2/geometry.xml b/tests/regression_tests/filter_distribcell/case-2/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/geometry.xml rename to tests/regression_tests/filter_distribcell/case-2/geometry.xml diff --git a/tests/test_filter_distribcell/case-2/materials.xml b/tests/regression_tests/filter_distribcell/case-2/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/materials.xml rename to tests/regression_tests/filter_distribcell/case-2/materials.xml diff --git a/tests/test_filter_distribcell/case-2/results_true.dat b/tests/regression_tests/filter_distribcell/case-2/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-2/results_true.dat rename to tests/regression_tests/filter_distribcell/case-2/results_true.dat diff --git a/tests/test_filter_distribcell/case-2/settings.xml b/tests/regression_tests/filter_distribcell/case-2/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/settings.xml rename to tests/regression_tests/filter_distribcell/case-2/settings.xml diff --git a/tests/test_filter_distribcell/case-2/tallies.xml b/tests/regression_tests/filter_distribcell/case-2/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-2/tallies.xml rename to tests/regression_tests/filter_distribcell/case-2/tallies.xml diff --git a/tests/test_filter_distribcell/case-3/geometry.xml b/tests/regression_tests/filter_distribcell/case-3/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/geometry.xml rename to tests/regression_tests/filter_distribcell/case-3/geometry.xml diff --git a/tests/test_filter_distribcell/case-3/materials.xml b/tests/regression_tests/filter_distribcell/case-3/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/materials.xml rename to tests/regression_tests/filter_distribcell/case-3/materials.xml diff --git a/tests/test_filter_distribcell/case-3/results_true.dat b/tests/regression_tests/filter_distribcell/case-3/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-3/results_true.dat rename to tests/regression_tests/filter_distribcell/case-3/results_true.dat diff --git a/tests/test_filter_distribcell/case-3/settings.xml b/tests/regression_tests/filter_distribcell/case-3/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/settings.xml rename to tests/regression_tests/filter_distribcell/case-3/settings.xml diff --git a/tests/test_filter_distribcell/case-3/tallies.xml b/tests/regression_tests/filter_distribcell/case-3/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-3/tallies.xml rename to tests/regression_tests/filter_distribcell/case-3/tallies.xml diff --git a/tests/test_filter_distribcell/case-4/geometry.xml b/tests/regression_tests/filter_distribcell/case-4/geometry.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/geometry.xml rename to tests/regression_tests/filter_distribcell/case-4/geometry.xml diff --git a/tests/test_filter_distribcell/case-4/materials.xml b/tests/regression_tests/filter_distribcell/case-4/materials.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/materials.xml rename to tests/regression_tests/filter_distribcell/case-4/materials.xml diff --git a/tests/test_filter_distribcell/case-4/results_true.dat b/tests/regression_tests/filter_distribcell/case-4/results_true.dat similarity index 100% rename from tests/test_filter_distribcell/case-4/results_true.dat rename to tests/regression_tests/filter_distribcell/case-4/results_true.dat diff --git a/tests/test_filter_distribcell/case-4/settings.xml b/tests/regression_tests/filter_distribcell/case-4/settings.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/settings.xml rename to tests/regression_tests/filter_distribcell/case-4/settings.xml diff --git a/tests/test_filter_distribcell/case-4/tallies.xml b/tests/regression_tests/filter_distribcell/case-4/tallies.xml similarity index 100% rename from tests/test_filter_distribcell/case-4/tallies.xml rename to tests/regression_tests/filter_distribcell/case-4/tallies.xml diff --git a/tests/test_filter_distribcell/test_filter_distribcell.py b/tests/regression_tests/filter_distribcell/test.py similarity index 98% rename from tests/test_filter_distribcell/test_filter_distribcell.py rename to tests/regression_tests/filter_distribcell/test.py index f0fc270399..320a808a5f 100644 --- a/tests/test_filter_distribcell/test_filter_distribcell.py +++ b/tests/regression_tests/filter_distribcell/test.py @@ -4,7 +4,7 @@ import glob import hashlib import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import * diff --git a/tests/test_filter_energyfun/inputs_true.dat b/tests/regression_tests/filter_energyfun/inputs_true.dat similarity index 100% rename from tests/test_filter_energyfun/inputs_true.dat rename to tests/regression_tests/filter_energyfun/inputs_true.dat diff --git a/tests/test_filter_energyfun/results_true.dat b/tests/regression_tests/filter_energyfun/results_true.dat similarity index 100% rename from tests/test_filter_energyfun/results_true.dat rename to tests/regression_tests/filter_energyfun/results_true.dat diff --git a/tests/test_filter_energyfun/test_filter_energyfun.py b/tests/regression_tests/filter_energyfun/test.py similarity index 97% rename from tests/test_filter_energyfun/test_filter_energyfun.py rename to tests/regression_tests/filter_energyfun/test.py index 7e787edff2..1de522f540 100644 --- a/tests/test_filter_energyfun/test_filter_energyfun.py +++ b/tests/regression_tests/filter_energyfun/test.py @@ -3,7 +3,7 @@ import os import sys import glob -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_filter_mesh/inputs_true.dat b/tests/regression_tests/filter_mesh/inputs_true.dat similarity index 100% rename from tests/test_filter_mesh/inputs_true.dat rename to tests/regression_tests/filter_mesh/inputs_true.dat diff --git a/tests/test_filter_mesh/results_true.dat b/tests/regression_tests/filter_mesh/results_true.dat similarity index 100% rename from tests/test_filter_mesh/results_true.dat rename to tests/regression_tests/filter_mesh/results_true.dat diff --git a/tests/test_filter_mesh/test_filter_mesh.py b/tests/regression_tests/filter_mesh/test.py similarity index 97% rename from tests/test_filter_mesh/test_filter_mesh.py rename to tests/regression_tests/filter_mesh/test.py index 7b9e8bd16b..4ad5e9005b 100644 --- a/tests/test_filter_mesh/test_filter_mesh.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import HashedPyAPITestHarness import openmc diff --git a/tests/test_fixed_source/inputs_true.dat b/tests/regression_tests/fixed_source/inputs_true.dat similarity index 100% rename from tests/test_fixed_source/inputs_true.dat rename to tests/regression_tests/fixed_source/inputs_true.dat diff --git a/tests/test_fixed_source/results_true.dat b/tests/regression_tests/fixed_source/results_true.dat similarity index 100% rename from tests/test_fixed_source/results_true.dat rename to tests/regression_tests/fixed_source/results_true.dat diff --git a/tests/test_fixed_source/test_fixed_source.py b/tests/regression_tests/fixed_source/test.py similarity index 97% rename from tests/test_fixed_source/test_fixed_source.py rename to tests/regression_tests/fixed_source/test.py index db58e2f706..3e28610fb0 100644 --- a/tests/test_fixed_source/test_fixed_source.py +++ b/tests/regression_tests/fixed_source/test.py @@ -4,7 +4,7 @@ import glob import os import sys import numpy as np -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.stats diff --git a/tests/test_infinite_cell/geometry.xml b/tests/regression_tests/infinite_cell/geometry.xml similarity index 100% rename from tests/test_infinite_cell/geometry.xml rename to tests/regression_tests/infinite_cell/geometry.xml diff --git a/tests/test_infinite_cell/materials.xml b/tests/regression_tests/infinite_cell/materials.xml similarity index 100% rename from tests/test_infinite_cell/materials.xml rename to tests/regression_tests/infinite_cell/materials.xml diff --git a/tests/test_infinite_cell/results_true.dat b/tests/regression_tests/infinite_cell/results_true.dat similarity index 100% rename from tests/test_infinite_cell/results_true.dat rename to tests/regression_tests/infinite_cell/results_true.dat diff --git a/tests/test_infinite_cell/settings.xml b/tests/regression_tests/infinite_cell/settings.xml similarity index 100% rename from tests/test_infinite_cell/settings.xml rename to tests/regression_tests/infinite_cell/settings.xml diff --git a/tests/regression_tests/infinite_cell/test.py b/tests/regression_tests/infinite_cell/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/infinite_cell/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_iso_in_lab/inputs_true.dat b/tests/regression_tests/iso_in_lab/inputs_true.dat similarity index 100% rename from tests/test_iso_in_lab/inputs_true.dat rename to tests/regression_tests/iso_in_lab/inputs_true.dat diff --git a/tests/test_iso_in_lab/results_true.dat b/tests/regression_tests/iso_in_lab/results_true.dat similarity index 100% rename from tests/test_iso_in_lab/results_true.dat rename to tests/regression_tests/iso_in_lab/results_true.dat diff --git a/tests/test_iso_in_lab/test_iso_in_lab.py b/tests/regression_tests/iso_in_lab/test.py similarity index 83% rename from tests/test_iso_in_lab/test_iso_in_lab.py rename to tests/regression_tests/iso_in_lab/test.py index 60b5bc2dee..8cc9c7b7d7 100644 --- a/tests/test_iso_in_lab/test_iso_in_lab.py +++ b/tests/regression_tests/iso_in_lab/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness diff --git a/tests/test_lattice/geometry.xml b/tests/regression_tests/lattice/geometry.xml similarity index 100% rename from tests/test_lattice/geometry.xml rename to tests/regression_tests/lattice/geometry.xml diff --git a/tests/test_lattice/materials.xml b/tests/regression_tests/lattice/materials.xml similarity index 100% rename from tests/test_lattice/materials.xml rename to tests/regression_tests/lattice/materials.xml diff --git a/tests/test_lattice/results_true.dat b/tests/regression_tests/lattice/results_true.dat similarity index 100% rename from tests/test_lattice/results_true.dat rename to tests/regression_tests/lattice/results_true.dat diff --git a/tests/test_lattice/settings.xml b/tests/regression_tests/lattice/settings.xml similarity index 100% rename from tests/test_lattice/settings.xml rename to tests/regression_tests/lattice/settings.xml diff --git a/tests/regression_tests/lattice/test.py b/tests/regression_tests/lattice/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/lattice/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_lattice_hex/geometry.xml b/tests/regression_tests/lattice_hex/geometry.xml similarity index 100% rename from tests/test_lattice_hex/geometry.xml rename to tests/regression_tests/lattice_hex/geometry.xml diff --git a/tests/test_lattice_hex/materials.xml b/tests/regression_tests/lattice_hex/materials.xml similarity index 100% rename from tests/test_lattice_hex/materials.xml rename to tests/regression_tests/lattice_hex/materials.xml diff --git a/tests/test_lattice_hex/plots.xml b/tests/regression_tests/lattice_hex/plots.xml similarity index 100% rename from tests/test_lattice_hex/plots.xml rename to tests/regression_tests/lattice_hex/plots.xml diff --git a/tests/test_lattice_hex/results_true.dat b/tests/regression_tests/lattice_hex/results_true.dat similarity index 100% rename from tests/test_lattice_hex/results_true.dat rename to tests/regression_tests/lattice_hex/results_true.dat diff --git a/tests/test_lattice_hex/settings.xml b/tests/regression_tests/lattice_hex/settings.xml similarity index 100% rename from tests/test_lattice_hex/settings.xml rename to tests/regression_tests/lattice_hex/settings.xml diff --git a/tests/regression_tests/lattice_hex/test.py b/tests/regression_tests/lattice_hex/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/lattice_hex/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_lattice_mixed/geometry.xml b/tests/regression_tests/lattice_mixed/geometry.xml similarity index 100% rename from tests/test_lattice_mixed/geometry.xml rename to tests/regression_tests/lattice_mixed/geometry.xml diff --git a/tests/test_lattice_mixed/materials.xml b/tests/regression_tests/lattice_mixed/materials.xml similarity index 100% rename from tests/test_lattice_mixed/materials.xml rename to tests/regression_tests/lattice_mixed/materials.xml diff --git a/tests/test_lattice_mixed/plots.xml b/tests/regression_tests/lattice_mixed/plots.xml similarity index 100% rename from tests/test_lattice_mixed/plots.xml rename to tests/regression_tests/lattice_mixed/plots.xml diff --git a/tests/test_lattice_mixed/results_true.dat b/tests/regression_tests/lattice_mixed/results_true.dat similarity index 100% rename from tests/test_lattice_mixed/results_true.dat rename to tests/regression_tests/lattice_mixed/results_true.dat diff --git a/tests/test_lattice_mixed/settings.xml b/tests/regression_tests/lattice_mixed/settings.xml similarity index 100% rename from tests/test_lattice_mixed/settings.xml rename to tests/regression_tests/lattice_mixed/settings.xml diff --git a/tests/regression_tests/lattice_mixed/test.py b/tests/regression_tests/lattice_mixed/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/lattice_mixed/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_lattice_multiple/geometry.xml b/tests/regression_tests/lattice_multiple/geometry.xml similarity index 100% rename from tests/test_lattice_multiple/geometry.xml rename to tests/regression_tests/lattice_multiple/geometry.xml diff --git a/tests/test_lattice_multiple/materials.xml b/tests/regression_tests/lattice_multiple/materials.xml similarity index 100% rename from tests/test_lattice_multiple/materials.xml rename to tests/regression_tests/lattice_multiple/materials.xml diff --git a/tests/test_lattice_multiple/results_true.dat b/tests/regression_tests/lattice_multiple/results_true.dat similarity index 100% rename from tests/test_lattice_multiple/results_true.dat rename to tests/regression_tests/lattice_multiple/results_true.dat diff --git a/tests/test_lattice_multiple/settings.xml b/tests/regression_tests/lattice_multiple/settings.xml similarity index 100% rename from tests/test_lattice_multiple/settings.xml rename to tests/regression_tests/lattice_multiple/settings.xml diff --git a/tests/regression_tests/lattice_multiple/test.py b/tests/regression_tests/lattice_multiple/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/lattice_multiple/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_mg_basic/inputs_true.dat b/tests/regression_tests/mg_basic/inputs_true.dat similarity index 98% rename from tests/test_mg_basic/inputs_true.dat rename to tests/regression_tests/mg_basic/inputs_true.dat index 220b1de240..a0efdbde0f 100644 --- a/tests/test_mg_basic/inputs_true.dat +++ b/tests/regression_tests/mg_basic/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_basic/results_true.dat b/tests/regression_tests/mg_basic/results_true.dat similarity index 100% rename from tests/test_mg_basic/results_true.dat rename to tests/regression_tests/mg_basic/results_true.dat diff --git a/tests/test_mg_basic/test_mg_basic.py b/tests/regression_tests/mg_basic/test.py similarity index 82% rename from tests/test_mg_basic/test_mg_basic.py rename to tests/regression_tests/mg_basic/test.py index 21871efd72..054503f9ab 100644 --- a/tests/test_mg_basic/test_mg_basic.py +++ b/tests/regression_tests/mg_basic/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness from openmc.examples import slab_mg diff --git a/tests/test_mg_convert/inputs_true.dat b/tests/regression_tests/mg_convert/inputs_true.dat similarity index 100% rename from tests/test_mg_convert/inputs_true.dat rename to tests/regression_tests/mg_convert/inputs_true.dat diff --git a/tests/test_mg_convert/results_true.dat b/tests/regression_tests/mg_convert/results_true.dat similarity index 100% rename from tests/test_mg_convert/results_true.dat rename to tests/regression_tests/mg_convert/results_true.dat diff --git a/tests/test_mg_convert/test_mg_convert.py b/tests/regression_tests/mg_convert/test.py similarity index 99% rename from tests/test_mg_convert/test_mg_convert.py rename to tests/regression_tests/mg_convert/test.py index 36bfe5338b..45f701ff11 100755 --- a/tests/test_mg_convert/test_mg_convert.py +++ b/tests/regression_tests/mg_convert/test.py @@ -3,7 +3,7 @@ import os import sys import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) import numpy as np diff --git a/tests/test_mg_legendre/inputs_true.dat b/tests/regression_tests/mg_legendre/inputs_true.dat similarity index 96% rename from tests/test_mg_legendre/inputs_true.dat rename to tests/regression_tests/mg_legendre/inputs_true.dat index 9b63fb944c..7548080955 100644 --- a/tests/test_mg_legendre/inputs_true.dat +++ b/tests/regression_tests/mg_legendre/inputs_true.dat @@ -14,7 +14,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_legendre/results_true.dat b/tests/regression_tests/mg_legendre/results_true.dat similarity index 100% rename from tests/test_mg_legendre/results_true.dat rename to tests/regression_tests/mg_legendre/results_true.dat diff --git a/tests/test_mg_legendre/test_mg_legendre.py b/tests/regression_tests/mg_legendre/test.py similarity index 85% rename from tests/test_mg_legendre/test_mg_legendre.py rename to tests/regression_tests/mg_legendre/test.py index eee0f0800f..2e574afb61 100644 --- a/tests/test_mg_legendre/test_mg_legendre.py +++ b/tests/regression_tests/mg_legendre/test.py @@ -3,7 +3,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness from openmc.examples import slab_mg diff --git a/tests/test_mg_max_order/inputs_true.dat b/tests/regression_tests/mg_max_order/inputs_true.dat similarity index 96% rename from tests/test_mg_max_order/inputs_true.dat rename to tests/regression_tests/mg_max_order/inputs_true.dat index 3954bc73a7..023d468d4f 100644 --- a/tests/test_mg_max_order/inputs_true.dat +++ b/tests/regression_tests/mg_max_order/inputs_true.dat @@ -14,7 +14,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_max_order/results_true.dat b/tests/regression_tests/mg_max_order/results_true.dat similarity index 100% rename from tests/test_mg_max_order/results_true.dat rename to tests/regression_tests/mg_max_order/results_true.dat diff --git a/tests/test_mg_max_order/test_mg_max_order.py b/tests/regression_tests/mg_max_order/test.py similarity index 84% rename from tests/test_mg_max_order/test_mg_max_order.py rename to tests/regression_tests/mg_max_order/test.py index 8ac0f58785..21fd2c0b64 100644 --- a/tests/test_mg_max_order/test_mg_max_order.py +++ b/tests/regression_tests/mg_max_order/test.py @@ -3,7 +3,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness from openmc.examples import slab_mg diff --git a/tests/test_mg_nuclide/inputs_true.dat b/tests/regression_tests/mg_nuclide/inputs_true.dat similarity index 98% rename from tests/test_mg_nuclide/inputs_true.dat rename to tests/regression_tests/mg_nuclide/inputs_true.dat index d42b15480d..e11b9e3f07 100644 --- a/tests/test_mg_nuclide/inputs_true.dat +++ b/tests/regression_tests/mg_nuclide/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_nuclide/results_true.dat b/tests/regression_tests/mg_nuclide/results_true.dat similarity index 100% rename from tests/test_mg_nuclide/results_true.dat rename to tests/regression_tests/mg_nuclide/results_true.dat diff --git a/tests/test_mg_nuclide/test_mg_nuclide.py b/tests/regression_tests/mg_nuclide/test.py similarity index 82% rename from tests/test_mg_nuclide/test_mg_nuclide.py rename to tests/regression_tests/mg_nuclide/test.py index 0f3c9dd6d7..d1c06cd417 100644 --- a/tests/test_mg_nuclide/test_mg_nuclide.py +++ b/tests/regression_tests/mg_nuclide/test.py @@ -3,7 +3,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness from openmc.examples import slab_mg diff --git a/tests/test_mg_survival_biasing/inputs_true.dat b/tests/regression_tests/mg_survival_biasing/inputs_true.dat similarity index 98% rename from tests/test_mg_survival_biasing/inputs_true.dat rename to tests/regression_tests/mg_survival_biasing/inputs_true.dat index 057af68105..4bc79d48e3 100644 --- a/tests/test_mg_survival_biasing/inputs_true.dat +++ b/tests/regression_tests/mg_survival_biasing/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_survival_biasing/results_true.dat b/tests/regression_tests/mg_survival_biasing/results_true.dat similarity index 100% rename from tests/test_mg_survival_biasing/results_true.dat rename to tests/regression_tests/mg_survival_biasing/results_true.dat diff --git a/tests/test_mg_survival_biasing/test_mg_survival_biasing.py b/tests/regression_tests/mg_survival_biasing/test.py similarity index 84% rename from tests/test_mg_survival_biasing/test_mg_survival_biasing.py rename to tests/regression_tests/mg_survival_biasing/test.py index 9886ad3e49..2669201c0e 100644 --- a/tests/test_mg_survival_biasing/test_mg_survival_biasing.py +++ b/tests/regression_tests/mg_survival_biasing/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness from openmc.examples import slab_mg diff --git a/tests/test_mg_tallies/inputs_true.dat b/tests/regression_tests/mg_tallies/inputs_true.dat similarity index 99% rename from tests/test_mg_tallies/inputs_true.dat rename to tests/regression_tests/mg_tallies/inputs_true.dat index 0c71689aea..7b5067014f 100644 --- a/tests/test_mg_tallies/inputs_true.dat +++ b/tests/regression_tests/mg_tallies/inputs_true.dat @@ -32,7 +32,7 @@ - ../1d_mgxs.h5 + ../../1d_mgxs.h5 diff --git a/tests/test_mg_tallies/results_true.dat b/tests/regression_tests/mg_tallies/results_true.dat similarity index 100% rename from tests/test_mg_tallies/results_true.dat rename to tests/regression_tests/mg_tallies/results_true.dat diff --git a/tests/test_mg_tallies/test_mg_tallies.py b/tests/regression_tests/mg_tallies/test.py similarity index 98% rename from tests/test_mg_tallies/test_mg_tallies.py rename to tests/regression_tests/mg_tallies/test.py index aeafae3182..ec7081e2ad 100644 --- a/tests/test_mg_tallies/test_mg_tallies.py +++ b/tests/regression_tests/mg_tallies/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import HashedPyAPITestHarness import openmc from openmc.examples import slab_mg diff --git a/tests/test_mgxs_library_ce_to_mg/inputs_true.dat b/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_ce_to_mg/inputs_true.dat rename to tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat diff --git a/tests/test_mgxs_library_ce_to_mg/results_true.dat b/tests/regression_tests/mgxs_library_ce_to_mg/results_true.dat similarity index 100% rename from tests/test_mgxs_library_ce_to_mg/results_true.dat rename to tests/regression_tests/mgxs_library_ce_to_mg/results_true.dat diff --git a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py similarity index 98% rename from tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py rename to tests/regression_tests/mgxs_library_ce_to_mg/test.py index 7ae47636e6..e29cf58313 100644 --- a/tests/test_mgxs_library_ce_to_mg/test_mgxs_library_ce_to_mg.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -3,7 +3,7 @@ import os import sys import glob -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_condense/inputs_true.dat b/tests/regression_tests/mgxs_library_condense/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_condense/inputs_true.dat rename to tests/regression_tests/mgxs_library_condense/inputs_true.dat diff --git a/tests/test_mgxs_library_condense/results_true.dat b/tests/regression_tests/mgxs_library_condense/results_true.dat similarity index 100% rename from tests/test_mgxs_library_condense/results_true.dat rename to tests/regression_tests/mgxs_library_condense/results_true.dat diff --git a/tests/test_mgxs_library_condense/test_mgxs_library_condense.py b/tests/regression_tests/mgxs_library_condense/test.py similarity index 97% rename from tests/test_mgxs_library_condense/test_mgxs_library_condense.py rename to tests/regression_tests/mgxs_library_condense/test.py index 127980da6e..fd144636f9 100644 --- a/tests/test_mgxs_library_condense/test_mgxs_library_condense.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_distribcell/inputs_true.dat b/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_distribcell/inputs_true.dat rename to tests/regression_tests/mgxs_library_distribcell/inputs_true.dat diff --git a/tests/test_mgxs_library_distribcell/results_true.dat b/tests/regression_tests/mgxs_library_distribcell/results_true.dat similarity index 100% rename from tests/test_mgxs_library_distribcell/results_true.dat rename to tests/regression_tests/mgxs_library_distribcell/results_true.dat diff --git a/tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py b/tests/regression_tests/mgxs_library_distribcell/test.py similarity index 97% rename from tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py rename to tests/regression_tests/mgxs_library_distribcell/test.py index 38f16c5884..e59f4c7578 100644 --- a/tests/test_mgxs_library_distribcell/test_mgxs_library_distribcell.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_hdf5/inputs_true.dat b/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_hdf5/inputs_true.dat rename to tests/regression_tests/mgxs_library_hdf5/inputs_true.dat diff --git a/tests/test_mgxs_library_hdf5/results_true.dat b/tests/regression_tests/mgxs_library_hdf5/results_true.dat similarity index 100% rename from tests/test_mgxs_library_hdf5/results_true.dat rename to tests/regression_tests/mgxs_library_hdf5/results_true.dat diff --git a/tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py b/tests/regression_tests/mgxs_library_hdf5/test.py similarity index 98% rename from tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py rename to tests/regression_tests/mgxs_library_hdf5/test.py index 31a9d96126..8daf828cea 100644 --- a/tests/test_mgxs_library_hdf5/test_mgxs_library_hdf5.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -8,7 +8,7 @@ import hashlib import numpy as np import h5py -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_mesh/inputs_true.dat b/tests/regression_tests/mgxs_library_mesh/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_mesh/inputs_true.dat rename to tests/regression_tests/mgxs_library_mesh/inputs_true.dat diff --git a/tests/test_mgxs_library_mesh/results_true.dat b/tests/regression_tests/mgxs_library_mesh/results_true.dat similarity index 100% rename from tests/test_mgxs_library_mesh/results_true.dat rename to tests/regression_tests/mgxs_library_mesh/results_true.dat diff --git a/tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py b/tests/regression_tests/mgxs_library_mesh/test.py similarity index 97% rename from tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py rename to tests/regression_tests/mgxs_library_mesh/test.py index e0a3307bc3..06cb10601b 100644 --- a/tests/test_mgxs_library_mesh/test_mgxs_library_mesh.py +++ b/tests/regression_tests/mgxs_library_mesh/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_no_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_no_nuclides/inputs_true.dat rename to tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat diff --git a/tests/test_mgxs_library_no_nuclides/results_true.dat b/tests/regression_tests/mgxs_library_no_nuclides/results_true.dat similarity index 100% rename from tests/test_mgxs_library_no_nuclides/results_true.dat rename to tests/regression_tests/mgxs_library_no_nuclides/results_true.dat diff --git a/tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py similarity index 97% rename from tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py rename to tests/regression_tests/mgxs_library_no_nuclides/test.py index 793cfc7146..ede916059c 100644 --- a/tests/test_mgxs_library_no_nuclides/test_mgxs_library_no_nuclides.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_mgxs_library_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat similarity index 100% rename from tests/test_mgxs_library_nuclides/inputs_true.dat rename to tests/regression_tests/mgxs_library_nuclides/inputs_true.dat diff --git a/tests/test_mgxs_library_nuclides/results_true.dat b/tests/regression_tests/mgxs_library_nuclides/results_true.dat similarity index 100% rename from tests/test_mgxs_library_nuclides/results_true.dat rename to tests/regression_tests/mgxs_library_nuclides/results_true.dat diff --git a/tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py b/tests/regression_tests/mgxs_library_nuclides/test.py similarity index 97% rename from tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py rename to tests/regression_tests/mgxs_library_nuclides/test.py index 9e54e1bb6b..e668ab52cc 100644 --- a/tests/test_mgxs_library_nuclides/test_mgxs_library_nuclides.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.mgxs diff --git a/tests/test_multipole/inputs_true.dat b/tests/regression_tests/multipole/inputs_true.dat similarity index 100% rename from tests/test_multipole/inputs_true.dat rename to tests/regression_tests/multipole/inputs_true.dat diff --git a/tests/test_multipole/results_true.dat b/tests/regression_tests/multipole/results_true.dat similarity index 100% rename from tests/test_multipole/results_true.dat rename to tests/regression_tests/multipole/results_true.dat diff --git a/tests/test_multipole/test_multipole.py b/tests/regression_tests/multipole/test.py similarity index 98% rename from tests/test_multipole/test_multipole.py rename to tests/regression_tests/multipole/test.py index 294185312a..20da97f7c0 100644 --- a/tests/test_multipole/test_multipole.py +++ b/tests/regression_tests/multipole/test.py @@ -1,7 +1,7 @@ #!/usr/bin/env python import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness, PyAPITestHarness import openmc import openmc.model diff --git a/tests/test_output/geometry.xml b/tests/regression_tests/output/geometry.xml similarity index 100% rename from tests/test_output/geometry.xml rename to tests/regression_tests/output/geometry.xml diff --git a/tests/test_output/materials.xml b/tests/regression_tests/output/materials.xml similarity index 100% rename from tests/test_output/materials.xml rename to tests/regression_tests/output/materials.xml diff --git a/tests/test_output/results_true.dat b/tests/regression_tests/output/results_true.dat similarity index 100% rename from tests/test_output/results_true.dat rename to tests/regression_tests/output/results_true.dat diff --git a/tests/test_output/settings.xml b/tests/regression_tests/output/settings.xml similarity index 100% rename from tests/test_output/settings.xml rename to tests/regression_tests/output/settings.xml diff --git a/tests/test_output/test_output.py b/tests/regression_tests/output/test.py similarity index 94% rename from tests/test_output/test_output.py rename to tests/regression_tests/output/test.py index 475b3e9f02..0092f54919 100644 --- a/tests/test_output/test_output.py +++ b/tests/regression_tests/output/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_particle_restart_eigval/geometry.xml b/tests/regression_tests/particle_restart_eigval/geometry.xml similarity index 100% rename from tests/test_particle_restart_eigval/geometry.xml rename to tests/regression_tests/particle_restart_eigval/geometry.xml diff --git a/tests/test_particle_restart_eigval/materials.xml b/tests/regression_tests/particle_restart_eigval/materials.xml similarity index 100% rename from tests/test_particle_restart_eigval/materials.xml rename to tests/regression_tests/particle_restart_eigval/materials.xml diff --git a/tests/test_particle_restart_eigval/results_true.dat b/tests/regression_tests/particle_restart_eigval/results_true.dat similarity index 100% rename from tests/test_particle_restart_eigval/results_true.dat rename to tests/regression_tests/particle_restart_eigval/results_true.dat diff --git a/tests/test_particle_restart_eigval/settings.xml b/tests/regression_tests/particle_restart_eigval/settings.xml similarity index 100% rename from tests/test_particle_restart_eigval/settings.xml rename to tests/regression_tests/particle_restart_eigval/settings.xml diff --git a/tests/test_particle_restart_eigval/test_particle_restart_eigval.py b/tests/regression_tests/particle_restart_eigval/test.py similarity index 79% rename from tests/test_particle_restart_eigval/test_particle_restart_eigval.py rename to tests/regression_tests/particle_restart_eigval/test.py index 1ebbd3ea53..455ff9e927 100644 --- a/tests/test_particle_restart_eigval/test_particle_restart_eigval.py +++ b/tests/regression_tests/particle_restart_eigval/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import ParticleRestartTestHarness diff --git a/tests/test_particle_restart_fixed/geometry.xml b/tests/regression_tests/particle_restart_fixed/geometry.xml similarity index 100% rename from tests/test_particle_restart_fixed/geometry.xml rename to tests/regression_tests/particle_restart_fixed/geometry.xml diff --git a/tests/test_particle_restart_fixed/materials.xml b/tests/regression_tests/particle_restart_fixed/materials.xml similarity index 100% rename from tests/test_particle_restart_fixed/materials.xml rename to tests/regression_tests/particle_restart_fixed/materials.xml diff --git a/tests/test_particle_restart_fixed/results_true.dat b/tests/regression_tests/particle_restart_fixed/results_true.dat similarity index 100% rename from tests/test_particle_restart_fixed/results_true.dat rename to tests/regression_tests/particle_restart_fixed/results_true.dat diff --git a/tests/test_particle_restart_fixed/settings.xml b/tests/regression_tests/particle_restart_fixed/settings.xml similarity index 100% rename from tests/test_particle_restart_fixed/settings.xml rename to tests/regression_tests/particle_restart_fixed/settings.xml diff --git a/tests/test_particle_restart_fixed/test_particle_restart_fixed.py b/tests/regression_tests/particle_restart_fixed/test.py similarity index 79% rename from tests/test_particle_restart_fixed/test_particle_restart_fixed.py rename to tests/regression_tests/particle_restart_fixed/test.py index df0398c6eb..e473fdb59e 100644 --- a/tests/test_particle_restart_fixed/test_particle_restart_fixed.py +++ b/tests/regression_tests/particle_restart_fixed/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import ParticleRestartTestHarness diff --git a/tests/test_periodic/inputs_true.dat b/tests/regression_tests/periodic/inputs_true.dat similarity index 100% rename from tests/test_periodic/inputs_true.dat rename to tests/regression_tests/periodic/inputs_true.dat diff --git a/tests/test_periodic/results_true.dat b/tests/regression_tests/periodic/results_true.dat similarity index 100% rename from tests/test_periodic/results_true.dat rename to tests/regression_tests/periodic/results_true.dat diff --git a/tests/test_periodic/test_periodic.py b/tests/regression_tests/periodic/test.py similarity index 97% rename from tests/test_periodic/test_periodic.py rename to tests/regression_tests/periodic/test.py index 3883654c13..ddd7cd89b8 100644 --- a/tests/test_periodic/test_periodic.py +++ b/tests/regression_tests/periodic/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_plot/geometry.xml b/tests/regression_tests/plot/geometry.xml similarity index 100% rename from tests/test_plot/geometry.xml rename to tests/regression_tests/plot/geometry.xml diff --git a/tests/test_plot/materials.xml b/tests/regression_tests/plot/materials.xml similarity index 100% rename from tests/test_plot/materials.xml rename to tests/regression_tests/plot/materials.xml diff --git a/tests/test_plot/plots.xml b/tests/regression_tests/plot/plots.xml similarity index 100% rename from tests/test_plot/plots.xml rename to tests/regression_tests/plot/plots.xml diff --git a/tests/test_plot/results_true.dat b/tests/regression_tests/plot/results_true.dat similarity index 100% rename from tests/test_plot/results_true.dat rename to tests/regression_tests/plot/results_true.dat diff --git a/tests/test_plot/settings.xml b/tests/regression_tests/plot/settings.xml similarity index 100% rename from tests/test_plot/settings.xml rename to tests/regression_tests/plot/settings.xml diff --git a/tests/test_plot/test_plot.py b/tests/regression_tests/plot/test.py similarity index 97% rename from tests/test_plot/test_plot.py rename to tests/regression_tests/plot/test.py index 1a99c24886..d0c362ef2b 100644 --- a/tests/test_plot/test_plot.py +++ b/tests/regression_tests/plot/test.py @@ -4,7 +4,7 @@ import glob import hashlib import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness import h5py diff --git a/tests/test_ptables_off/geometry.xml b/tests/regression_tests/ptables_off/geometry.xml similarity index 100% rename from tests/test_ptables_off/geometry.xml rename to tests/regression_tests/ptables_off/geometry.xml diff --git a/tests/test_ptables_off/materials.xml b/tests/regression_tests/ptables_off/materials.xml similarity index 100% rename from tests/test_ptables_off/materials.xml rename to tests/regression_tests/ptables_off/materials.xml diff --git a/tests/test_ptables_off/results_true.dat b/tests/regression_tests/ptables_off/results_true.dat similarity index 100% rename from tests/test_ptables_off/results_true.dat rename to tests/regression_tests/ptables_off/results_true.dat diff --git a/tests/test_ptables_off/settings.xml b/tests/regression_tests/ptables_off/settings.xml similarity index 100% rename from tests/test_ptables_off/settings.xml rename to tests/regression_tests/ptables_off/settings.xml diff --git a/tests/regression_tests/ptables_off/test.py b/tests/regression_tests/ptables_off/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/ptables_off/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_quadric_surfaces/geometry.xml b/tests/regression_tests/quadric_surfaces/geometry.xml similarity index 100% rename from tests/test_quadric_surfaces/geometry.xml rename to tests/regression_tests/quadric_surfaces/geometry.xml diff --git a/tests/test_quadric_surfaces/materials.xml b/tests/regression_tests/quadric_surfaces/materials.xml similarity index 100% rename from tests/test_quadric_surfaces/materials.xml rename to tests/regression_tests/quadric_surfaces/materials.xml diff --git a/tests/test_quadric_surfaces/results_true.dat b/tests/regression_tests/quadric_surfaces/results_true.dat similarity index 100% rename from tests/test_quadric_surfaces/results_true.dat rename to tests/regression_tests/quadric_surfaces/results_true.dat diff --git a/tests/test_quadric_surfaces/settings.xml b/tests/regression_tests/quadric_surfaces/settings.xml similarity index 100% rename from tests/test_quadric_surfaces/settings.xml rename to tests/regression_tests/quadric_surfaces/settings.xml diff --git a/tests/regression_tests/quadric_surfaces/test.py b/tests/regression_tests/quadric_surfaces/test.py new file mode 100755 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/quadric_surfaces/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_reflective_plane/geometry.xml b/tests/regression_tests/reflective_plane/geometry.xml similarity index 100% rename from tests/test_reflective_plane/geometry.xml rename to tests/regression_tests/reflective_plane/geometry.xml diff --git a/tests/test_reflective_plane/materials.xml b/tests/regression_tests/reflective_plane/materials.xml similarity index 100% rename from tests/test_reflective_plane/materials.xml rename to tests/regression_tests/reflective_plane/materials.xml diff --git a/tests/test_reflective_plane/results_true.dat b/tests/regression_tests/reflective_plane/results_true.dat similarity index 100% rename from tests/test_reflective_plane/results_true.dat rename to tests/regression_tests/reflective_plane/results_true.dat diff --git a/tests/test_reflective_plane/settings.xml b/tests/regression_tests/reflective_plane/settings.xml similarity index 100% rename from tests/test_reflective_plane/settings.xml rename to tests/regression_tests/reflective_plane/settings.xml diff --git a/tests/regression_tests/reflective_plane/test.py b/tests/regression_tests/reflective_plane/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/reflective_plane/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_resonance_scattering/inputs_true.dat b/tests/regression_tests/resonance_scattering/inputs_true.dat similarity index 100% rename from tests/test_resonance_scattering/inputs_true.dat rename to tests/regression_tests/resonance_scattering/inputs_true.dat diff --git a/tests/test_resonance_scattering/results_true.dat b/tests/regression_tests/resonance_scattering/results_true.dat similarity index 100% rename from tests/test_resonance_scattering/results_true.dat rename to tests/regression_tests/resonance_scattering/results_true.dat diff --git a/tests/test_resonance_scattering/test_resonance_scattering.py b/tests/regression_tests/resonance_scattering/test.py similarity index 96% rename from tests/test_resonance_scattering/test_resonance_scattering.py rename to tests/regression_tests/resonance_scattering/test.py index 94c9f5c3de..3ed7fe2272 100644 --- a/tests/test_resonance_scattering/test_resonance_scattering.py +++ b/tests/regression_tests/resonance_scattering/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_rotation/geometry.xml b/tests/regression_tests/rotation/geometry.xml similarity index 100% rename from tests/test_rotation/geometry.xml rename to tests/regression_tests/rotation/geometry.xml diff --git a/tests/test_rotation/materials.xml b/tests/regression_tests/rotation/materials.xml similarity index 100% rename from tests/test_rotation/materials.xml rename to tests/regression_tests/rotation/materials.xml diff --git a/tests/test_rotation/results_true.dat b/tests/regression_tests/rotation/results_true.dat similarity index 100% rename from tests/test_rotation/results_true.dat rename to tests/regression_tests/rotation/results_true.dat diff --git a/tests/test_rotation/settings.xml b/tests/regression_tests/rotation/settings.xml similarity index 100% rename from tests/test_rotation/settings.xml rename to tests/regression_tests/rotation/settings.xml diff --git a/tests/regression_tests/rotation/test.py b/tests/regression_tests/rotation/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/rotation/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_salphabeta/inputs_true.dat b/tests/regression_tests/salphabeta/inputs_true.dat similarity index 100% rename from tests/test_salphabeta/inputs_true.dat rename to tests/regression_tests/salphabeta/inputs_true.dat diff --git a/tests/test_salphabeta/results_true.dat b/tests/regression_tests/salphabeta/results_true.dat similarity index 100% rename from tests/test_salphabeta/results_true.dat rename to tests/regression_tests/salphabeta/results_true.dat diff --git a/tests/test_salphabeta/test_salphabeta.py b/tests/regression_tests/salphabeta/test.py similarity index 97% rename from tests/test_salphabeta/test_salphabeta.py rename to tests/regression_tests/salphabeta/test.py index 600c703324..6ced79a8d6 100644 --- a/tests/test_salphabeta/test_salphabeta.py +++ b/tests/regression_tests/salphabeta/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_score_current/geometry.xml b/tests/regression_tests/score_current/geometry.xml similarity index 100% rename from tests/test_score_current/geometry.xml rename to tests/regression_tests/score_current/geometry.xml diff --git a/tests/test_score_current/materials.xml b/tests/regression_tests/score_current/materials.xml similarity index 100% rename from tests/test_score_current/materials.xml rename to tests/regression_tests/score_current/materials.xml diff --git a/tests/test_score_current/results_true.dat b/tests/regression_tests/score_current/results_true.dat similarity index 100% rename from tests/test_score_current/results_true.dat rename to tests/regression_tests/score_current/results_true.dat diff --git a/tests/test_score_current/settings.xml b/tests/regression_tests/score_current/settings.xml similarity index 100% rename from tests/test_score_current/settings.xml rename to tests/regression_tests/score_current/settings.xml diff --git a/tests/test_score_current/tallies.xml b/tests/regression_tests/score_current/tallies.xml similarity index 100% rename from tests/test_score_current/tallies.xml rename to tests/regression_tests/score_current/tallies.xml diff --git a/tests/test_score_current/test_score_current.py b/tests/regression_tests/score_current/test.py similarity index 77% rename from tests/test_score_current/test_score_current.py rename to tests/regression_tests/score_current/test.py index ea5886a639..70ddc22198 100644 --- a/tests/test_score_current/test_score_current.py +++ b/tests/regression_tests/score_current/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import HashedTestHarness diff --git a/tests/test_seed/geometry.xml b/tests/regression_tests/seed/geometry.xml similarity index 100% rename from tests/test_seed/geometry.xml rename to tests/regression_tests/seed/geometry.xml diff --git a/tests/test_seed/materials.xml b/tests/regression_tests/seed/materials.xml similarity index 100% rename from tests/test_seed/materials.xml rename to tests/regression_tests/seed/materials.xml diff --git a/tests/test_seed/results_true.dat b/tests/regression_tests/seed/results_true.dat similarity index 100% rename from tests/test_seed/results_true.dat rename to tests/regression_tests/seed/results_true.dat diff --git a/tests/test_seed/settings.xml b/tests/regression_tests/seed/settings.xml similarity index 100% rename from tests/test_seed/settings.xml rename to tests/regression_tests/seed/settings.xml diff --git a/tests/regression_tests/seed/test.py b/tests/regression_tests/seed/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/seed/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_source/inputs_true.dat b/tests/regression_tests/source/inputs_true.dat similarity index 100% rename from tests/test_source/inputs_true.dat rename to tests/regression_tests/source/inputs_true.dat diff --git a/tests/test_source/results_true.dat b/tests/regression_tests/source/results_true.dat similarity index 100% rename from tests/test_source/results_true.dat rename to tests/regression_tests/source/results_true.dat diff --git a/tests/test_source/test_source.py b/tests/regression_tests/source/test.py similarity index 97% rename from tests/test_source/test_source.py rename to tests/regression_tests/source/test.py index a872ab4816..7a3d054d8e 100644 --- a/tests/test_source/test_source.py +++ b/tests/regression_tests/source/test.py @@ -6,7 +6,7 @@ import sys import numpy as np -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_source_file/geometry.xml b/tests/regression_tests/source_file/geometry.xml similarity index 100% rename from tests/test_source_file/geometry.xml rename to tests/regression_tests/source_file/geometry.xml diff --git a/tests/test_source_file/materials.xml b/tests/regression_tests/source_file/materials.xml similarity index 100% rename from tests/test_source_file/materials.xml rename to tests/regression_tests/source_file/materials.xml diff --git a/tests/test_source_file/results_true.dat b/tests/regression_tests/source_file/results_true.dat similarity index 100% rename from tests/test_source_file/results_true.dat rename to tests/regression_tests/source_file/results_true.dat diff --git a/tests/test_source_file/settings.xml b/tests/regression_tests/source_file/settings.xml similarity index 100% rename from tests/test_source_file/settings.xml rename to tests/regression_tests/source_file/settings.xml diff --git a/tests/test_source_file/test_source_file.py b/tests/regression_tests/source_file/test.py similarity index 98% rename from tests/test_source_file/test_source_file.py rename to tests/regression_tests/source_file/test.py index 5631814b4c..f04441a208 100644 --- a/tests/test_source_file/test_source_file.py +++ b/tests/regression_tests/source_file/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import * diff --git a/tests/test_sourcepoint_batch/geometry.xml b/tests/regression_tests/sourcepoint_batch/geometry.xml similarity index 100% rename from tests/test_sourcepoint_batch/geometry.xml rename to tests/regression_tests/sourcepoint_batch/geometry.xml diff --git a/tests/test_sourcepoint_batch/materials.xml b/tests/regression_tests/sourcepoint_batch/materials.xml similarity index 100% rename from tests/test_sourcepoint_batch/materials.xml rename to tests/regression_tests/sourcepoint_batch/materials.xml diff --git a/tests/test_sourcepoint_batch/results_true.dat b/tests/regression_tests/sourcepoint_batch/results_true.dat similarity index 100% rename from tests/test_sourcepoint_batch/results_true.dat rename to tests/regression_tests/sourcepoint_batch/results_true.dat diff --git a/tests/test_sourcepoint_batch/settings.xml b/tests/regression_tests/sourcepoint_batch/settings.xml similarity index 100% rename from tests/test_sourcepoint_batch/settings.xml rename to tests/regression_tests/sourcepoint_batch/settings.xml diff --git a/tests/test_sourcepoint_batch/test_sourcepoint_batch.py b/tests/regression_tests/sourcepoint_batch/test.py similarity index 95% rename from tests/test_sourcepoint_batch/test_sourcepoint_batch.py rename to tests/regression_tests/sourcepoint_batch/test.py index d5ea0e48b2..1239a00dcd 100644 --- a/tests/test_sourcepoint_batch/test_sourcepoint_batch.py +++ b/tests/regression_tests/sourcepoint_batch/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness from openmc import StatePoint diff --git a/tests/test_sourcepoint_latest/geometry.xml b/tests/regression_tests/sourcepoint_latest/geometry.xml similarity index 100% rename from tests/test_sourcepoint_latest/geometry.xml rename to tests/regression_tests/sourcepoint_latest/geometry.xml diff --git a/tests/test_sourcepoint_latest/materials.xml b/tests/regression_tests/sourcepoint_latest/materials.xml similarity index 100% rename from tests/test_sourcepoint_latest/materials.xml rename to tests/regression_tests/sourcepoint_latest/materials.xml diff --git a/tests/test_sourcepoint_latest/results_true.dat b/tests/regression_tests/sourcepoint_latest/results_true.dat similarity index 100% rename from tests/test_sourcepoint_latest/results_true.dat rename to tests/regression_tests/sourcepoint_latest/results_true.dat diff --git a/tests/test_sourcepoint_latest/settings.xml b/tests/regression_tests/sourcepoint_latest/settings.xml similarity index 100% rename from tests/test_sourcepoint_latest/settings.xml rename to tests/regression_tests/sourcepoint_latest/settings.xml diff --git a/tests/test_sourcepoint_latest/test_sourcepoint_latest.py b/tests/regression_tests/sourcepoint_latest/test.py similarity index 91% rename from tests/test_sourcepoint_latest/test_sourcepoint_latest.py rename to tests/regression_tests/sourcepoint_latest/test.py index c64cc20cc7..4af176eecd 100644 --- a/tests/test_sourcepoint_latest/test_sourcepoint_latest.py +++ b/tests/regression_tests/sourcepoint_latest/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_sourcepoint_restart/geometry.xml b/tests/regression_tests/sourcepoint_restart/geometry.xml similarity index 100% rename from tests/test_sourcepoint_restart/geometry.xml rename to tests/regression_tests/sourcepoint_restart/geometry.xml diff --git a/tests/test_sourcepoint_restart/materials.xml b/tests/regression_tests/sourcepoint_restart/materials.xml similarity index 100% rename from tests/test_sourcepoint_restart/materials.xml rename to tests/regression_tests/sourcepoint_restart/materials.xml diff --git a/tests/test_sourcepoint_restart/results_true.dat b/tests/regression_tests/sourcepoint_restart/results_true.dat similarity index 100% rename from tests/test_sourcepoint_restart/results_true.dat rename to tests/regression_tests/sourcepoint_restart/results_true.dat diff --git a/tests/test_sourcepoint_restart/settings.xml b/tests/regression_tests/sourcepoint_restart/settings.xml similarity index 100% rename from tests/test_sourcepoint_restart/settings.xml rename to tests/regression_tests/sourcepoint_restart/settings.xml diff --git a/tests/test_sourcepoint_restart/tallies.xml b/tests/regression_tests/sourcepoint_restart/tallies.xml similarity index 100% rename from tests/test_sourcepoint_restart/tallies.xml rename to tests/regression_tests/sourcepoint_restart/tallies.xml diff --git a/tests/regression_tests/sourcepoint_restart/test.py b/tests/regression_tests/sourcepoint_restart/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/sourcepoint_restart/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_statepoint_batch/geometry.xml b/tests/regression_tests/statepoint_batch/geometry.xml similarity index 100% rename from tests/test_statepoint_batch/geometry.xml rename to tests/regression_tests/statepoint_batch/geometry.xml diff --git a/tests/test_statepoint_batch/materials.xml b/tests/regression_tests/statepoint_batch/materials.xml similarity index 100% rename from tests/test_statepoint_batch/materials.xml rename to tests/regression_tests/statepoint_batch/materials.xml diff --git a/tests/test_statepoint_batch/results_true.dat b/tests/regression_tests/statepoint_batch/results_true.dat similarity index 100% rename from tests/test_statepoint_batch/results_true.dat rename to tests/regression_tests/statepoint_batch/results_true.dat diff --git a/tests/test_statepoint_batch/settings.xml b/tests/regression_tests/statepoint_batch/settings.xml similarity index 100% rename from tests/test_statepoint_batch/settings.xml rename to tests/regression_tests/statepoint_batch/settings.xml diff --git a/tests/test_statepoint_batch/test_statepoint_batch.py b/tests/regression_tests/statepoint_batch/test.py similarity index 91% rename from tests/test_statepoint_batch/test_statepoint_batch.py rename to tests/regression_tests/statepoint_batch/test.py index e3e2391ba1..0820aa6f01 100644 --- a/tests/test_statepoint_batch/test_statepoint_batch.py +++ b/tests/regression_tests/statepoint_batch/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_statepoint_restart/geometry.xml b/tests/regression_tests/statepoint_restart/geometry.xml similarity index 100% rename from tests/test_statepoint_restart/geometry.xml rename to tests/regression_tests/statepoint_restart/geometry.xml diff --git a/tests/test_statepoint_restart/materials.xml b/tests/regression_tests/statepoint_restart/materials.xml similarity index 100% rename from tests/test_statepoint_restart/materials.xml rename to tests/regression_tests/statepoint_restart/materials.xml diff --git a/tests/test_statepoint_restart/results_true.dat b/tests/regression_tests/statepoint_restart/results_true.dat similarity index 100% rename from tests/test_statepoint_restart/results_true.dat rename to tests/regression_tests/statepoint_restart/results_true.dat diff --git a/tests/test_statepoint_restart/settings.xml b/tests/regression_tests/statepoint_restart/settings.xml similarity index 100% rename from tests/test_statepoint_restart/settings.xml rename to tests/regression_tests/statepoint_restart/settings.xml diff --git a/tests/test_statepoint_restart/tallies.xml b/tests/regression_tests/statepoint_restart/tallies.xml similarity index 100% rename from tests/test_statepoint_restart/tallies.xml rename to tests/regression_tests/statepoint_restart/tallies.xml diff --git a/tests/test_statepoint_restart/test_statepoint_restart.py b/tests/regression_tests/statepoint_restart/test.py similarity index 97% rename from tests/test_statepoint_restart/test_statepoint_restart.py rename to tests/regression_tests/statepoint_restart/test.py index 9c10551dea..f3a52c1cf0 100644 --- a/tests/test_statepoint_restart/test_statepoint_restart.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness import openmc diff --git a/tests/test_statepoint_sourcesep/geometry.xml b/tests/regression_tests/statepoint_sourcesep/geometry.xml similarity index 100% rename from tests/test_statepoint_sourcesep/geometry.xml rename to tests/regression_tests/statepoint_sourcesep/geometry.xml diff --git a/tests/test_statepoint_sourcesep/materials.xml b/tests/regression_tests/statepoint_sourcesep/materials.xml similarity index 100% rename from tests/test_statepoint_sourcesep/materials.xml rename to tests/regression_tests/statepoint_sourcesep/materials.xml diff --git a/tests/test_statepoint_sourcesep/results_true.dat b/tests/regression_tests/statepoint_sourcesep/results_true.dat similarity index 100% rename from tests/test_statepoint_sourcesep/results_true.dat rename to tests/regression_tests/statepoint_sourcesep/results_true.dat diff --git a/tests/test_statepoint_sourcesep/settings.xml b/tests/regression_tests/statepoint_sourcesep/settings.xml similarity index 100% rename from tests/test_statepoint_sourcesep/settings.xml rename to tests/regression_tests/statepoint_sourcesep/settings.xml diff --git a/tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py b/tests/regression_tests/statepoint_sourcesep/test.py similarity index 94% rename from tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py rename to tests/regression_tests/statepoint_sourcesep/test.py index f4bdcfb7b3..904fa471e8 100644 --- a/tests/test_statepoint_sourcesep/test_statepoint_sourcesep.py +++ b/tests/regression_tests/statepoint_sourcesep/test.py @@ -3,7 +3,7 @@ import glob import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_surface_tally/inputs_true.dat b/tests/regression_tests/surface_tally/inputs_true.dat similarity index 100% rename from tests/test_surface_tally/inputs_true.dat rename to tests/regression_tests/surface_tally/inputs_true.dat diff --git a/tests/test_surface_tally/results_true.dat b/tests/regression_tests/surface_tally/results_true.dat similarity index 100% rename from tests/test_surface_tally/results_true.dat rename to tests/regression_tests/surface_tally/results_true.dat diff --git a/tests/test_surface_tally/test_surface_tally.py b/tests/regression_tests/surface_tally/test.py similarity index 99% rename from tests/test_surface_tally/test_surface_tally.py rename to tests/regression_tests/surface_tally/test.py index ae525a6838..9729fdf20d 100644 --- a/tests/test_surface_tally/test_surface_tally.py +++ b/tests/regression_tests/surface_tally/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import numpy as np import openmc diff --git a/tests/test_survival_biasing/geometry.xml b/tests/regression_tests/survival_biasing/geometry.xml similarity index 100% rename from tests/test_survival_biasing/geometry.xml rename to tests/regression_tests/survival_biasing/geometry.xml diff --git a/tests/test_survival_biasing/materials.xml b/tests/regression_tests/survival_biasing/materials.xml similarity index 100% rename from tests/test_survival_biasing/materials.xml rename to tests/regression_tests/survival_biasing/materials.xml diff --git a/tests/test_survival_biasing/results_true.dat b/tests/regression_tests/survival_biasing/results_true.dat similarity index 100% rename from tests/test_survival_biasing/results_true.dat rename to tests/regression_tests/survival_biasing/results_true.dat diff --git a/tests/test_survival_biasing/settings.xml b/tests/regression_tests/survival_biasing/settings.xml similarity index 100% rename from tests/test_survival_biasing/settings.xml rename to tests/regression_tests/survival_biasing/settings.xml diff --git a/tests/test_survival_biasing/tallies.xml b/tests/regression_tests/survival_biasing/tallies.xml similarity index 100% rename from tests/test_survival_biasing/tallies.xml rename to tests/regression_tests/survival_biasing/tallies.xml diff --git a/tests/regression_tests/survival_biasing/test.py b/tests/regression_tests/survival_biasing/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/survival_biasing/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_tallies/inputs_true.dat b/tests/regression_tests/tallies/inputs_true.dat similarity index 100% rename from tests/test_tallies/inputs_true.dat rename to tests/regression_tests/tallies/inputs_true.dat diff --git a/tests/test_tallies/results_true.dat b/tests/regression_tests/tallies/results_true.dat similarity index 100% rename from tests/test_tallies/results_true.dat rename to tests/regression_tests/tallies/results_true.dat diff --git a/tests/test_tallies/test_tallies.py b/tests/regression_tests/tallies/test.py similarity index 99% rename from tests/test_tallies/test_tallies.py rename to tests/regression_tests/tallies/test.py index 577d2babc0..693e941af1 100644 --- a/tests/test_tallies/test_tallies.py +++ b/tests/regression_tests/tallies/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import HashedPyAPITestHarness from openmc.filter import * diff --git a/tests/test_tally_aggregation/inputs_true.dat b/tests/regression_tests/tally_aggregation/inputs_true.dat similarity index 100% rename from tests/test_tally_aggregation/inputs_true.dat rename to tests/regression_tests/tally_aggregation/inputs_true.dat diff --git a/tests/test_tally_aggregation/results_true.dat b/tests/regression_tests/tally_aggregation/results_true.dat similarity index 100% rename from tests/test_tally_aggregation/results_true.dat rename to tests/regression_tests/tally_aggregation/results_true.dat diff --git a/tests/test_tally_aggregation/test_tally_aggregation.py b/tests/regression_tests/tally_aggregation/test.py similarity index 97% rename from tests/test_tally_aggregation/test_tally_aggregation.py rename to tests/regression_tests/tally_aggregation/test.py index cf291e0266..62d3a3f041 100644 --- a/tests/test_tally_aggregation/test_tally_aggregation.py +++ b/tests/regression_tests/tally_aggregation/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_tally_arithmetic/inputs_true.dat b/tests/regression_tests/tally_arithmetic/inputs_true.dat similarity index 100% rename from tests/test_tally_arithmetic/inputs_true.dat rename to tests/regression_tests/tally_arithmetic/inputs_true.dat diff --git a/tests/test_tally_arithmetic/results_true.dat b/tests/regression_tests/tally_arithmetic/results_true.dat similarity index 100% rename from tests/test_tally_arithmetic/results_true.dat rename to tests/regression_tests/tally_arithmetic/results_true.dat diff --git a/tests/test_tally_arithmetic/test_tally_arithmetic.py b/tests/regression_tests/tally_arithmetic/test.py similarity index 98% rename from tests/test_tally_arithmetic/test_tally_arithmetic.py rename to tests/regression_tests/tally_arithmetic/test.py index 593a0a2917..fab1b0fb2c 100644 --- a/tests/test_tally_arithmetic/test_tally_arithmetic.py +++ b/tests/regression_tests/tally_arithmetic/test.py @@ -4,7 +4,7 @@ import os import sys import glob import hashlib -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_tally_assumesep/geometry.xml b/tests/regression_tests/tally_assumesep/geometry.xml similarity index 100% rename from tests/test_tally_assumesep/geometry.xml rename to tests/regression_tests/tally_assumesep/geometry.xml diff --git a/tests/test_tally_assumesep/materials.xml b/tests/regression_tests/tally_assumesep/materials.xml similarity index 100% rename from tests/test_tally_assumesep/materials.xml rename to tests/regression_tests/tally_assumesep/materials.xml diff --git a/tests/test_tally_assumesep/results_true.dat b/tests/regression_tests/tally_assumesep/results_true.dat similarity index 100% rename from tests/test_tally_assumesep/results_true.dat rename to tests/regression_tests/tally_assumesep/results_true.dat diff --git a/tests/test_tally_assumesep/settings.xml b/tests/regression_tests/tally_assumesep/settings.xml similarity index 100% rename from tests/test_tally_assumesep/settings.xml rename to tests/regression_tests/tally_assumesep/settings.xml diff --git a/tests/test_tally_assumesep/tallies.xml b/tests/regression_tests/tally_assumesep/tallies.xml similarity index 100% rename from tests/test_tally_assumesep/tallies.xml rename to tests/regression_tests/tally_assumesep/tallies.xml diff --git a/tests/regression_tests/tally_assumesep/test.py b/tests/regression_tests/tally_assumesep/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/tally_assumesep/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_tally_nuclides/geometry.xml b/tests/regression_tests/tally_nuclides/geometry.xml similarity index 100% rename from tests/test_tally_nuclides/geometry.xml rename to tests/regression_tests/tally_nuclides/geometry.xml diff --git a/tests/test_tally_nuclides/materials.xml b/tests/regression_tests/tally_nuclides/materials.xml similarity index 100% rename from tests/test_tally_nuclides/materials.xml rename to tests/regression_tests/tally_nuclides/materials.xml diff --git a/tests/test_tally_nuclides/results_true.dat b/tests/regression_tests/tally_nuclides/results_true.dat similarity index 100% rename from tests/test_tally_nuclides/results_true.dat rename to tests/regression_tests/tally_nuclides/results_true.dat diff --git a/tests/test_tally_nuclides/settings.xml b/tests/regression_tests/tally_nuclides/settings.xml similarity index 100% rename from tests/test_tally_nuclides/settings.xml rename to tests/regression_tests/tally_nuclides/settings.xml diff --git a/tests/test_tally_nuclides/tallies.xml b/tests/regression_tests/tally_nuclides/tallies.xml similarity index 100% rename from tests/test_tally_nuclides/tallies.xml rename to tests/regression_tests/tally_nuclides/tallies.xml diff --git a/tests/regression_tests/tally_nuclides/test.py b/tests/regression_tests/tally_nuclides/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/tally_nuclides/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_tally_slice_merge/inputs_true.dat b/tests/regression_tests/tally_slice_merge/inputs_true.dat similarity index 100% rename from tests/test_tally_slice_merge/inputs_true.dat rename to tests/regression_tests/tally_slice_merge/inputs_true.dat diff --git a/tests/test_tally_slice_merge/results_true.dat b/tests/regression_tests/tally_slice_merge/results_true.dat similarity index 100% rename from tests/test_tally_slice_merge/results_true.dat rename to tests/regression_tests/tally_slice_merge/results_true.dat diff --git a/tests/test_tally_slice_merge/test_tally_slice_merge.py b/tests/regression_tests/tally_slice_merge/test.py similarity index 99% rename from tests/test_tally_slice_merge/test_tally_slice_merge.py rename to tests/regression_tests/tally_slice_merge/test.py index d917d2dadb..84908b5cbe 100644 --- a/tests/test_tally_slice_merge/test_tally_slice_merge.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -7,7 +7,7 @@ import sys import glob import hashlib import itertools -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_trace/geometry.xml b/tests/regression_tests/trace/geometry.xml similarity index 100% rename from tests/test_trace/geometry.xml rename to tests/regression_tests/trace/geometry.xml diff --git a/tests/test_trace/materials.xml b/tests/regression_tests/trace/materials.xml similarity index 100% rename from tests/test_trace/materials.xml rename to tests/regression_tests/trace/materials.xml diff --git a/tests/test_trace/results_true.dat b/tests/regression_tests/trace/results_true.dat similarity index 100% rename from tests/test_trace/results_true.dat rename to tests/regression_tests/trace/results_true.dat diff --git a/tests/test_trace/settings.xml b/tests/regression_tests/trace/settings.xml similarity index 100% rename from tests/test_trace/settings.xml rename to tests/regression_tests/trace/settings.xml diff --git a/tests/regression_tests/trace/test.py b/tests/regression_tests/trace/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/trace/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_track_output/geometry.xml b/tests/regression_tests/track_output/geometry.xml similarity index 100% rename from tests/test_track_output/geometry.xml rename to tests/regression_tests/track_output/geometry.xml diff --git a/tests/test_track_output/materials.xml b/tests/regression_tests/track_output/materials.xml similarity index 100% rename from tests/test_track_output/materials.xml rename to tests/regression_tests/track_output/materials.xml diff --git a/tests/test_track_output/results_true.dat b/tests/regression_tests/track_output/results_true.dat similarity index 100% rename from tests/test_track_output/results_true.dat rename to tests/regression_tests/track_output/results_true.dat diff --git a/tests/test_track_output/settings.xml b/tests/regression_tests/track_output/settings.xml similarity index 100% rename from tests/test_track_output/settings.xml rename to tests/regression_tests/track_output/settings.xml diff --git a/tests/test_track_output/test_track_output.py b/tests/regression_tests/track_output/test.py similarity index 96% rename from tests/test_track_output/test_track_output.py rename to tests/regression_tests/track_output/test.py index 0357aae19e..c7a2df4ebe 100644 --- a/tests/test_track_output/test_track_output.py +++ b/tests/regression_tests/track_output/test.py @@ -5,7 +5,7 @@ import os from subprocess import call import shutil import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_translation/geometry.xml b/tests/regression_tests/translation/geometry.xml similarity index 100% rename from tests/test_translation/geometry.xml rename to tests/regression_tests/translation/geometry.xml diff --git a/tests/test_translation/materials.xml b/tests/regression_tests/translation/materials.xml similarity index 100% rename from tests/test_translation/materials.xml rename to tests/regression_tests/translation/materials.xml diff --git a/tests/test_translation/results_true.dat b/tests/regression_tests/translation/results_true.dat similarity index 100% rename from tests/test_translation/results_true.dat rename to tests/regression_tests/translation/results_true.dat diff --git a/tests/test_translation/settings.xml b/tests/regression_tests/translation/settings.xml similarity index 100% rename from tests/test_translation/settings.xml rename to tests/regression_tests/translation/settings.xml diff --git a/tests/regression_tests/translation/test.py b/tests/regression_tests/translation/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/translation/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_trigger_batch_interval/geometry.xml b/tests/regression_tests/trigger_batch_interval/geometry.xml similarity index 100% rename from tests/test_trigger_batch_interval/geometry.xml rename to tests/regression_tests/trigger_batch_interval/geometry.xml diff --git a/tests/test_trigger_batch_interval/materials.xml b/tests/regression_tests/trigger_batch_interval/materials.xml similarity index 100% rename from tests/test_trigger_batch_interval/materials.xml rename to tests/regression_tests/trigger_batch_interval/materials.xml diff --git a/tests/test_trigger_batch_interval/results_true.dat b/tests/regression_tests/trigger_batch_interval/results_true.dat similarity index 100% rename from tests/test_trigger_batch_interval/results_true.dat rename to tests/regression_tests/trigger_batch_interval/results_true.dat diff --git a/tests/test_trigger_batch_interval/settings.xml b/tests/regression_tests/trigger_batch_interval/settings.xml similarity index 100% rename from tests/test_trigger_batch_interval/settings.xml rename to tests/regression_tests/trigger_batch_interval/settings.xml diff --git a/tests/test_trigger_batch_interval/tallies.xml b/tests/regression_tests/trigger_batch_interval/tallies.xml similarity index 100% rename from tests/test_trigger_batch_interval/tallies.xml rename to tests/regression_tests/trigger_batch_interval/tallies.xml diff --git a/tests/test_trigger_batch_interval/test_trigger_batch_interval.py b/tests/regression_tests/trigger_batch_interval/test.py similarity index 76% rename from tests/test_trigger_batch_interval/test_trigger_batch_interval.py rename to tests/regression_tests/trigger_batch_interval/test.py index fb88ada001..542c2ffdeb 100644 --- a/tests/test_trigger_batch_interval/test_trigger_batch_interval.py +++ b/tests/regression_tests/trigger_batch_interval/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_trigger_no_batch_interval/geometry.xml b/tests/regression_tests/trigger_no_batch_interval/geometry.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/geometry.xml rename to tests/regression_tests/trigger_no_batch_interval/geometry.xml diff --git a/tests/test_trigger_no_batch_interval/materials.xml b/tests/regression_tests/trigger_no_batch_interval/materials.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/materials.xml rename to tests/regression_tests/trigger_no_batch_interval/materials.xml diff --git a/tests/test_trigger_no_batch_interval/results_true.dat b/tests/regression_tests/trigger_no_batch_interval/results_true.dat similarity index 100% rename from tests/test_trigger_no_batch_interval/results_true.dat rename to tests/regression_tests/trigger_no_batch_interval/results_true.dat diff --git a/tests/test_trigger_no_batch_interval/settings.xml b/tests/regression_tests/trigger_no_batch_interval/settings.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/settings.xml rename to tests/regression_tests/trigger_no_batch_interval/settings.xml diff --git a/tests/test_trigger_no_batch_interval/tallies.xml b/tests/regression_tests/trigger_no_batch_interval/tallies.xml similarity index 100% rename from tests/test_trigger_no_batch_interval/tallies.xml rename to tests/regression_tests/trigger_no_batch_interval/tallies.xml diff --git a/tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py b/tests/regression_tests/trigger_no_batch_interval/test.py similarity index 76% rename from tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py rename to tests/regression_tests/trigger_no_batch_interval/test.py index fb88ada001..542c2ffdeb 100644 --- a/tests/test_trigger_no_batch_interval/test_trigger_no_batch_interval.py +++ b/tests/regression_tests/trigger_no_batch_interval/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_trigger_no_status/geometry.xml b/tests/regression_tests/trigger_no_status/geometry.xml similarity index 100% rename from tests/test_trigger_no_status/geometry.xml rename to tests/regression_tests/trigger_no_status/geometry.xml diff --git a/tests/test_trigger_no_status/materials.xml b/tests/regression_tests/trigger_no_status/materials.xml similarity index 100% rename from tests/test_trigger_no_status/materials.xml rename to tests/regression_tests/trigger_no_status/materials.xml diff --git a/tests/test_trigger_no_status/results_true.dat b/tests/regression_tests/trigger_no_status/results_true.dat similarity index 100% rename from tests/test_trigger_no_status/results_true.dat rename to tests/regression_tests/trigger_no_status/results_true.dat diff --git a/tests/test_trigger_no_status/settings.xml b/tests/regression_tests/trigger_no_status/settings.xml similarity index 100% rename from tests/test_trigger_no_status/settings.xml rename to tests/regression_tests/trigger_no_status/settings.xml diff --git a/tests/test_trigger_no_status/tallies.xml b/tests/regression_tests/trigger_no_status/tallies.xml similarity index 100% rename from tests/test_trigger_no_status/tallies.xml rename to tests/regression_tests/trigger_no_status/tallies.xml diff --git a/tests/regression_tests/trigger_no_status/test.py b/tests/regression_tests/trigger_no_status/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/trigger_no_status/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_trigger_tallies/geometry.xml b/tests/regression_tests/trigger_tallies/geometry.xml similarity index 100% rename from tests/test_trigger_tallies/geometry.xml rename to tests/regression_tests/trigger_tallies/geometry.xml diff --git a/tests/test_trigger_tallies/materials.xml b/tests/regression_tests/trigger_tallies/materials.xml similarity index 100% rename from tests/test_trigger_tallies/materials.xml rename to tests/regression_tests/trigger_tallies/materials.xml diff --git a/tests/test_trigger_tallies/results_true.dat b/tests/regression_tests/trigger_tallies/results_true.dat similarity index 100% rename from tests/test_trigger_tallies/results_true.dat rename to tests/regression_tests/trigger_tallies/results_true.dat diff --git a/tests/test_trigger_tallies/settings.xml b/tests/regression_tests/trigger_tallies/settings.xml similarity index 100% rename from tests/test_trigger_tallies/settings.xml rename to tests/regression_tests/trigger_tallies/settings.xml diff --git a/tests/test_trigger_tallies/tallies.xml b/tests/regression_tests/trigger_tallies/tallies.xml similarity index 100% rename from tests/test_trigger_tallies/tallies.xml rename to tests/regression_tests/trigger_tallies/tallies.xml diff --git a/tests/test_trigger_tallies/test_trigger_tallies.py b/tests/regression_tests/trigger_tallies/test.py similarity index 76% rename from tests/test_trigger_tallies/test_trigger_tallies.py rename to tests/regression_tests/trigger_tallies/test.py index fb88ada001..542c2ffdeb 100644 --- a/tests/test_trigger_tallies/test_trigger_tallies.py +++ b/tests/regression_tests/trigger_tallies/test.py @@ -2,7 +2,7 @@ import os import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import TestHarness diff --git a/tests/test_triso/inputs_true.dat b/tests/regression_tests/triso/inputs_true.dat similarity index 100% rename from tests/test_triso/inputs_true.dat rename to tests/regression_tests/triso/inputs_true.dat diff --git a/tests/test_triso/results_true.dat b/tests/regression_tests/triso/results_true.dat similarity index 100% rename from tests/test_triso/results_true.dat rename to tests/regression_tests/triso/results_true.dat diff --git a/tests/test_triso/test_triso.py b/tests/regression_tests/triso/test.py similarity index 98% rename from tests/test_triso/test_triso.py rename to tests/regression_tests/triso/test.py index e5c823c01f..c92495ace3 100644 --- a/tests/test_triso/test_triso.py +++ b/tests/regression_tests/triso/test.py @@ -8,7 +8,7 @@ from math import sqrt import numpy as np -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc import openmc.model diff --git a/tests/test_uniform_fs/geometry.xml b/tests/regression_tests/uniform_fs/geometry.xml similarity index 100% rename from tests/test_uniform_fs/geometry.xml rename to tests/regression_tests/uniform_fs/geometry.xml diff --git a/tests/test_uniform_fs/materials.xml b/tests/regression_tests/uniform_fs/materials.xml similarity index 100% rename from tests/test_uniform_fs/materials.xml rename to tests/regression_tests/uniform_fs/materials.xml diff --git a/tests/test_uniform_fs/results_true.dat b/tests/regression_tests/uniform_fs/results_true.dat similarity index 100% rename from tests/test_uniform_fs/results_true.dat rename to tests/regression_tests/uniform_fs/results_true.dat diff --git a/tests/test_uniform_fs/settings.xml b/tests/regression_tests/uniform_fs/settings.xml similarity index 100% rename from tests/test_uniform_fs/settings.xml rename to tests/regression_tests/uniform_fs/settings.xml diff --git a/tests/regression_tests/uniform_fs/test.py b/tests/regression_tests/uniform_fs/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/uniform_fs/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_universe/geometry.xml b/tests/regression_tests/universe/geometry.xml similarity index 100% rename from tests/test_universe/geometry.xml rename to tests/regression_tests/universe/geometry.xml diff --git a/tests/test_universe/materials.xml b/tests/regression_tests/universe/materials.xml similarity index 100% rename from tests/test_universe/materials.xml rename to tests/regression_tests/universe/materials.xml diff --git a/tests/test_universe/results_true.dat b/tests/regression_tests/universe/results_true.dat similarity index 100% rename from tests/test_universe/results_true.dat rename to tests/regression_tests/universe/results_true.dat diff --git a/tests/test_universe/settings.xml b/tests/regression_tests/universe/settings.xml similarity index 100% rename from tests/test_universe/settings.xml rename to tests/regression_tests/universe/settings.xml diff --git a/tests/regression_tests/universe/test.py b/tests/regression_tests/universe/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/universe/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_void/geometry.xml b/tests/regression_tests/void/geometry.xml similarity index 100% rename from tests/test_void/geometry.xml rename to tests/regression_tests/void/geometry.xml diff --git a/tests/test_void/materials.xml b/tests/regression_tests/void/materials.xml similarity index 100% rename from tests/test_void/materials.xml rename to tests/regression_tests/void/materials.xml diff --git a/tests/test_void/results_true.dat b/tests/regression_tests/void/results_true.dat similarity index 100% rename from tests/test_void/results_true.dat rename to tests/regression_tests/void/results_true.dat diff --git a/tests/test_void/settings.xml b/tests/regression_tests/void/settings.xml similarity index 100% rename from tests/test_void/settings.xml rename to tests/regression_tests/void/settings.xml diff --git a/tests/regression_tests/void/test.py b/tests/regression_tests/void/test.py new file mode 100644 index 0000000000..43f8e5ff0f --- /dev/null +++ b/tests/regression_tests/void/test.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import os +import sys +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) +from testing_harness import TestHarness + + +if __name__ == '__main__': + harness = TestHarness('statepoint.10.h5') + harness.main() diff --git a/tests/test_volume_calc/inputs_true.dat b/tests/regression_tests/volume_calc/inputs_true.dat similarity index 100% rename from tests/test_volume_calc/inputs_true.dat rename to tests/regression_tests/volume_calc/inputs_true.dat diff --git a/tests/test_volume_calc/results_true.dat b/tests/regression_tests/volume_calc/results_true.dat similarity index 100% rename from tests/test_volume_calc/results_true.dat rename to tests/regression_tests/volume_calc/results_true.dat diff --git a/tests/test_volume_calc/test_volume_calc.py b/tests/regression_tests/volume_calc/test.py similarity index 98% rename from tests/test_volume_calc/test_volume_calc.py rename to tests/regression_tests/volume_calc/test.py index 003528b0df..47ce27a122 100644 --- a/tests/test_volume_calc/test_volume_calc.py +++ b/tests/regression_tests/volume_calc/test.py @@ -3,7 +3,7 @@ import os import glob import sys -sys.path.insert(0, os.pardir) +sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from testing_harness import PyAPITestHarness import openmc diff --git a/tests/test_complex_cell/test_complex_cell.py b/tests/test_complex_cell/test_complex_cell.py deleted file mode 100755 index 0669165e25..0000000000 --- a/tests/test_complex_cell/test_complex_cell.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python - -import sys -sys.path.insert(0, '..') -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_infinite_cell/test_infinite_cell.py b/tests/test_infinite_cell/test_infinite_cell.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_infinite_cell/test_infinite_cell.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice/test_lattice.py b/tests/test_lattice/test_lattice.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice/test_lattice.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_hex/test_lattice_hex.py b/tests/test_lattice_hex/test_lattice_hex.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_hex/test_lattice_hex.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_mixed/test_lattice_mixed.py b/tests/test_lattice_mixed/test_lattice_mixed.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_mixed/test_lattice_mixed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_lattice_multiple/test_lattice_multiple.py b/tests/test_lattice_multiple/test_lattice_multiple.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_lattice_multiple/test_lattice_multiple.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_ptables_off/test_ptables_off.py b/tests/test_ptables_off/test_ptables_off.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_ptables_off/test_ptables_off.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_quadric_surfaces/test_quadric_surfaces.py b/tests/test_quadric_surfaces/test_quadric_surfaces.py deleted file mode 100755 index b04fcc6eba..0000000000 --- a/tests/test_quadric_surfaces/test_quadric_surfaces.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_reflective_plane/test_reflective_plane.py b/tests/test_reflective_plane/test_reflective_plane.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_reflective_plane/test_reflective_plane.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_rotation/test_rotation.py b/tests/test_rotation/test_rotation.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_rotation/test_rotation.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_seed/test_seed.py b/tests/test_seed/test_seed.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_seed/test_seed.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_sourcepoint_restart/test_sourcepoint_restart.py b/tests/test_sourcepoint_restart/test_sourcepoint_restart.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_sourcepoint_restart/test_sourcepoint_restart.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_survival_biasing/test_survival_biasing.py b/tests/test_survival_biasing/test_survival_biasing.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_survival_biasing/test_survival_biasing.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_tally_assumesep/test_tally_assumesep.py b/tests/test_tally_assumesep/test_tally_assumesep.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_tally_assumesep/test_tally_assumesep.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_tally_nuclides/test_tally_nuclides.py b/tests/test_tally_nuclides/test_tally_nuclides.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_tally_nuclides/test_tally_nuclides.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_trace/test_trace.py b/tests/test_trace/test_trace.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_trace/test_trace.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_translation/test_translation.py b/tests/test_translation/test_translation.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_translation/test_translation.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_trigger_no_status/test_trigger_no_status.py b/tests/test_trigger_no_status/test_trigger_no_status.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_trigger_no_status/test_trigger_no_status.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_uniform_fs/test_uniform_fs.py b/tests/test_uniform_fs/test_uniform_fs.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_uniform_fs/test_uniform_fs.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_universe/test_universe.py b/tests/test_universe/test_universe.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_universe/test_universe.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() diff --git a/tests/test_void/test_void.py b/tests/test_void/test_void.py deleted file mode 100644 index b04fcc6eba..0000000000 --- a/tests/test_void/test_void.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.pardir) -from testing_harness import TestHarness - - -if __name__ == '__main__': - harness = TestHarness('statepoint.10.h5') - harness.main() From 920afa123edf490a558099f21e0fe23a904db78c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 28 Jan 2018 15:57:52 -0600 Subject: [PATCH 048/212] Make tests directory a package (for pytest) --- setup.py | 2 +- tests/__init__.py | 0 tests/regression_tests/__init__.py | 0 tests/regression_tests/asymmetric_lattice/__init__.py | 0 tests/regression_tests/cmfd_feed/__init__.py | 0 tests/regression_tests/cmfd_nofeed/__init__.py | 0 tests/regression_tests/complex_cell/__init__.py | 0 tests/regression_tests/confidence_intervals/__init__.py | 0 tests/regression_tests/create_fission_neutrons/__init__.py | 0 tests/regression_tests/density/__init__.py | 0 tests/regression_tests/diff_tally/__init__.py | 0 tests/regression_tests/distribmat/__init__.py | 0 tests/regression_tests/eigenvalue_genperbatch/__init__.py | 0 tests/regression_tests/eigenvalue_no_inactive/__init__.py | 0 tests/regression_tests/energy_cutoff/__init__.py | 0 tests/regression_tests/energy_grid/__init__.py | 0 tests/regression_tests/energy_laws/__init__.py | 0 tests/regression_tests/enrichment/__init__.py | 0 tests/regression_tests/entropy/__init__.py | 0 tests/regression_tests/filter_distribcell/__init__.py | 0 tests/regression_tests/filter_energyfun/__init__.py | 0 tests/regression_tests/filter_mesh/__init__.py | 0 tests/regression_tests/fixed_source/__init__.py | 0 tests/regression_tests/infinite_cell/__init__.py | 0 tests/regression_tests/iso_in_lab/__init__.py | 0 tests/regression_tests/lattice/__init__.py | 0 tests/regression_tests/lattice_hex/__init__.py | 0 tests/regression_tests/lattice_mixed/__init__.py | 0 tests/regression_tests/lattice_multiple/__init__.py | 0 tests/regression_tests/mg_basic/__init__.py | 0 tests/regression_tests/mg_convert/__init__.py | 0 tests/regression_tests/mg_legendre/__init__.py | 0 tests/regression_tests/mg_max_order/__init__.py | 0 tests/regression_tests/mg_nuclide/__init__.py | 0 tests/regression_tests/mg_survival_biasing/__init__.py | 0 tests/regression_tests/mg_tallies/__init__.py | 0 tests/regression_tests/mgxs_library_ce_to_mg/__init__.py | 0 tests/regression_tests/mgxs_library_condense/__init__.py | 0 tests/regression_tests/mgxs_library_distribcell/__init__.py | 0 tests/regression_tests/mgxs_library_hdf5/__init__.py | 0 tests/regression_tests/mgxs_library_mesh/__init__.py | 0 tests/regression_tests/mgxs_library_no_nuclides/__init__.py | 0 tests/regression_tests/mgxs_library_nuclides/__init__.py | 0 tests/regression_tests/multipole/__init__.py | 0 tests/regression_tests/output/__init__.py | 0 tests/regression_tests/particle_restart_eigval/__init__.py | 0 tests/regression_tests/particle_restart_fixed/__init__.py | 0 tests/regression_tests/periodic/__init__.py | 0 tests/regression_tests/plot/__init__.py | 0 tests/regression_tests/ptables_off/__init__.py | 0 tests/regression_tests/quadric_surfaces/__init__.py | 0 tests/regression_tests/reflective_plane/__init__.py | 0 tests/regression_tests/resonance_scattering/__init__.py | 0 tests/regression_tests/rotation/__init__.py | 0 tests/regression_tests/salphabeta/__init__.py | 0 tests/regression_tests/score_current/__init__.py | 0 tests/regression_tests/seed/__init__.py | 0 tests/regression_tests/source/__init__.py | 0 tests/regression_tests/source_file/__init__.py | 0 tests/regression_tests/sourcepoint_batch/__init__.py | 0 tests/regression_tests/sourcepoint_latest/__init__.py | 0 tests/regression_tests/sourcepoint_restart/__init__.py | 0 tests/regression_tests/statepoint_batch/__init__.py | 0 tests/regression_tests/statepoint_restart/__init__.py | 0 tests/regression_tests/statepoint_sourcesep/__init__.py | 0 tests/regression_tests/surface_tally/__init__.py | 0 tests/regression_tests/survival_biasing/__init__.py | 0 tests/regression_tests/tallies/__init__.py | 0 tests/regression_tests/tally_aggregation/__init__.py | 0 tests/regression_tests/tally_arithmetic/__init__.py | 0 tests/regression_tests/tally_assumesep/__init__.py | 0 tests/regression_tests/tally_nuclides/__init__.py | 0 tests/regression_tests/tally_slice_merge/__init__.py | 0 tests/regression_tests/trace/__init__.py | 0 tests/regression_tests/track_output/__init__.py | 0 tests/regression_tests/translation/__init__.py | 0 tests/regression_tests/trigger_batch_interval/__init__.py | 0 tests/regression_tests/trigger_no_batch_interval/__init__.py | 0 tests/regression_tests/trigger_no_status/__init__.py | 0 tests/regression_tests/trigger_tallies/__init__.py | 0 tests/regression_tests/triso/__init__.py | 0 tests/regression_tests/uniform_fs/__init__.py | 0 tests/regression_tests/universe/__init__.py | 0 tests/regression_tests/void/__init__.py | 0 tests/regression_tests/volume_calc/__init__.py | 0 tests/unit_tests/__init__.py | 0 86 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 tests/__init__.py create mode 100644 tests/regression_tests/__init__.py create mode 100644 tests/regression_tests/asymmetric_lattice/__init__.py create mode 100644 tests/regression_tests/cmfd_feed/__init__.py create mode 100644 tests/regression_tests/cmfd_nofeed/__init__.py create mode 100644 tests/regression_tests/complex_cell/__init__.py create mode 100644 tests/regression_tests/confidence_intervals/__init__.py create mode 100644 tests/regression_tests/create_fission_neutrons/__init__.py create mode 100644 tests/regression_tests/density/__init__.py create mode 100644 tests/regression_tests/diff_tally/__init__.py create mode 100644 tests/regression_tests/distribmat/__init__.py create mode 100644 tests/regression_tests/eigenvalue_genperbatch/__init__.py create mode 100644 tests/regression_tests/eigenvalue_no_inactive/__init__.py create mode 100644 tests/regression_tests/energy_cutoff/__init__.py create mode 100644 tests/regression_tests/energy_grid/__init__.py create mode 100644 tests/regression_tests/energy_laws/__init__.py create mode 100644 tests/regression_tests/enrichment/__init__.py create mode 100644 tests/regression_tests/entropy/__init__.py create mode 100644 tests/regression_tests/filter_distribcell/__init__.py create mode 100644 tests/regression_tests/filter_energyfun/__init__.py create mode 100644 tests/regression_tests/filter_mesh/__init__.py create mode 100644 tests/regression_tests/fixed_source/__init__.py create mode 100644 tests/regression_tests/infinite_cell/__init__.py create mode 100644 tests/regression_tests/iso_in_lab/__init__.py create mode 100644 tests/regression_tests/lattice/__init__.py create mode 100644 tests/regression_tests/lattice_hex/__init__.py create mode 100644 tests/regression_tests/lattice_mixed/__init__.py create mode 100644 tests/regression_tests/lattice_multiple/__init__.py create mode 100644 tests/regression_tests/mg_basic/__init__.py create mode 100644 tests/regression_tests/mg_convert/__init__.py create mode 100644 tests/regression_tests/mg_legendre/__init__.py create mode 100644 tests/regression_tests/mg_max_order/__init__.py create mode 100644 tests/regression_tests/mg_nuclide/__init__.py create mode 100644 tests/regression_tests/mg_survival_biasing/__init__.py create mode 100644 tests/regression_tests/mg_tallies/__init__.py create mode 100644 tests/regression_tests/mgxs_library_ce_to_mg/__init__.py create mode 100644 tests/regression_tests/mgxs_library_condense/__init__.py create mode 100644 tests/regression_tests/mgxs_library_distribcell/__init__.py create mode 100644 tests/regression_tests/mgxs_library_hdf5/__init__.py create mode 100644 tests/regression_tests/mgxs_library_mesh/__init__.py create mode 100644 tests/regression_tests/mgxs_library_no_nuclides/__init__.py create mode 100644 tests/regression_tests/mgxs_library_nuclides/__init__.py create mode 100644 tests/regression_tests/multipole/__init__.py create mode 100644 tests/regression_tests/output/__init__.py create mode 100644 tests/regression_tests/particle_restart_eigval/__init__.py create mode 100644 tests/regression_tests/particle_restart_fixed/__init__.py create mode 100644 tests/regression_tests/periodic/__init__.py create mode 100644 tests/regression_tests/plot/__init__.py create mode 100644 tests/regression_tests/ptables_off/__init__.py create mode 100644 tests/regression_tests/quadric_surfaces/__init__.py create mode 100644 tests/regression_tests/reflective_plane/__init__.py create mode 100644 tests/regression_tests/resonance_scattering/__init__.py create mode 100644 tests/regression_tests/rotation/__init__.py create mode 100644 tests/regression_tests/salphabeta/__init__.py create mode 100644 tests/regression_tests/score_current/__init__.py create mode 100644 tests/regression_tests/seed/__init__.py create mode 100644 tests/regression_tests/source/__init__.py create mode 100644 tests/regression_tests/source_file/__init__.py create mode 100644 tests/regression_tests/sourcepoint_batch/__init__.py create mode 100644 tests/regression_tests/sourcepoint_latest/__init__.py create mode 100644 tests/regression_tests/sourcepoint_restart/__init__.py create mode 100644 tests/regression_tests/statepoint_batch/__init__.py create mode 100644 tests/regression_tests/statepoint_restart/__init__.py create mode 100644 tests/regression_tests/statepoint_sourcesep/__init__.py create mode 100644 tests/regression_tests/surface_tally/__init__.py create mode 100644 tests/regression_tests/survival_biasing/__init__.py create mode 100644 tests/regression_tests/tallies/__init__.py create mode 100644 tests/regression_tests/tally_aggregation/__init__.py create mode 100644 tests/regression_tests/tally_arithmetic/__init__.py create mode 100644 tests/regression_tests/tally_assumesep/__init__.py create mode 100644 tests/regression_tests/tally_nuclides/__init__.py create mode 100644 tests/regression_tests/tally_slice_merge/__init__.py create mode 100644 tests/regression_tests/trace/__init__.py create mode 100644 tests/regression_tests/track_output/__init__.py create mode 100644 tests/regression_tests/translation/__init__.py create mode 100644 tests/regression_tests/trigger_batch_interval/__init__.py create mode 100644 tests/regression_tests/trigger_no_batch_interval/__init__.py create mode 100644 tests/regression_tests/trigger_no_status/__init__.py create mode 100644 tests/regression_tests/trigger_tallies/__init__.py create mode 100644 tests/regression_tests/triso/__init__.py create mode 100644 tests/regression_tests/uniform_fs/__init__.py create mode 100644 tests/regression_tests/universe/__init__.py create mode 100644 tests/regression_tests/void/__init__.py create mode 100644 tests/regression_tests/volume_calc/__init__.py create mode 100644 tests/unit_tests/__init__.py diff --git a/setup.py b/setup.py index 338fe5fec8..7bffc516f0 100755 --- a/setup.py +++ b/setup.py @@ -26,7 +26,7 @@ with open('openmc/__init__.py', 'r') as f: kwargs = { 'name': 'openmc', 'version': version, - 'packages': find_packages(), + 'packages': find_packages(exclude=['tests*']), 'scripts': glob.glob('scripts/openmc-*'), # Data files and librarries diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/__init__.py b/tests/regression_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/asymmetric_lattice/__init__.py b/tests/regression_tests/asymmetric_lattice/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/cmfd_feed/__init__.py b/tests/regression_tests/cmfd_feed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/cmfd_nofeed/__init__.py b/tests/regression_tests/cmfd_nofeed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/complex_cell/__init__.py b/tests/regression_tests/complex_cell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/confidence_intervals/__init__.py b/tests/regression_tests/confidence_intervals/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/create_fission_neutrons/__init__.py b/tests/regression_tests/create_fission_neutrons/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/density/__init__.py b/tests/regression_tests/density/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/diff_tally/__init__.py b/tests/regression_tests/diff_tally/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/distribmat/__init__.py b/tests/regression_tests/distribmat/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/eigenvalue_genperbatch/__init__.py b/tests/regression_tests/eigenvalue_genperbatch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/eigenvalue_no_inactive/__init__.py b/tests/regression_tests/eigenvalue_no_inactive/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/energy_cutoff/__init__.py b/tests/regression_tests/energy_cutoff/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/energy_grid/__init__.py b/tests/regression_tests/energy_grid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/energy_laws/__init__.py b/tests/regression_tests/energy_laws/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/enrichment/__init__.py b/tests/regression_tests/enrichment/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/entropy/__init__.py b/tests/regression_tests/entropy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/filter_distribcell/__init__.py b/tests/regression_tests/filter_distribcell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/filter_energyfun/__init__.py b/tests/regression_tests/filter_energyfun/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/filter_mesh/__init__.py b/tests/regression_tests/filter_mesh/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/fixed_source/__init__.py b/tests/regression_tests/fixed_source/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/infinite_cell/__init__.py b/tests/regression_tests/infinite_cell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/iso_in_lab/__init__.py b/tests/regression_tests/iso_in_lab/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/lattice/__init__.py b/tests/regression_tests/lattice/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/lattice_hex/__init__.py b/tests/regression_tests/lattice_hex/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/lattice_mixed/__init__.py b/tests/regression_tests/lattice_mixed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/lattice_multiple/__init__.py b/tests/regression_tests/lattice_multiple/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_basic/__init__.py b/tests/regression_tests/mg_basic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_convert/__init__.py b/tests/regression_tests/mg_convert/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_legendre/__init__.py b/tests/regression_tests/mg_legendre/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_max_order/__init__.py b/tests/regression_tests/mg_max_order/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_nuclide/__init__.py b/tests/regression_tests/mg_nuclide/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_survival_biasing/__init__.py b/tests/regression_tests/mg_survival_biasing/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mg_tallies/__init__.py b/tests/regression_tests/mg_tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/__init__.py b/tests/regression_tests/mgxs_library_ce_to_mg/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_condense/__init__.py b/tests/regression_tests/mgxs_library_condense/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_distribcell/__init__.py b/tests/regression_tests/mgxs_library_distribcell/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_hdf5/__init__.py b/tests/regression_tests/mgxs_library_hdf5/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_mesh/__init__.py b/tests/regression_tests/mgxs_library_mesh/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_no_nuclides/__init__.py b/tests/regression_tests/mgxs_library_no_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/mgxs_library_nuclides/__init__.py b/tests/regression_tests/mgxs_library_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/multipole/__init__.py b/tests/regression_tests/multipole/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/output/__init__.py b/tests/regression_tests/output/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/particle_restart_eigval/__init__.py b/tests/regression_tests/particle_restart_eigval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/particle_restart_fixed/__init__.py b/tests/regression_tests/particle_restart_fixed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/periodic/__init__.py b/tests/regression_tests/periodic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/plot/__init__.py b/tests/regression_tests/plot/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/ptables_off/__init__.py b/tests/regression_tests/ptables_off/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/quadric_surfaces/__init__.py b/tests/regression_tests/quadric_surfaces/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/reflective_plane/__init__.py b/tests/regression_tests/reflective_plane/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/resonance_scattering/__init__.py b/tests/regression_tests/resonance_scattering/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/rotation/__init__.py b/tests/regression_tests/rotation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/salphabeta/__init__.py b/tests/regression_tests/salphabeta/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/score_current/__init__.py b/tests/regression_tests/score_current/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/seed/__init__.py b/tests/regression_tests/seed/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/source/__init__.py b/tests/regression_tests/source/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/source_file/__init__.py b/tests/regression_tests/source_file/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/sourcepoint_batch/__init__.py b/tests/regression_tests/sourcepoint_batch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/sourcepoint_latest/__init__.py b/tests/regression_tests/sourcepoint_latest/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/sourcepoint_restart/__init__.py b/tests/regression_tests/sourcepoint_restart/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/statepoint_batch/__init__.py b/tests/regression_tests/statepoint_batch/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/statepoint_restart/__init__.py b/tests/regression_tests/statepoint_restart/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/statepoint_sourcesep/__init__.py b/tests/regression_tests/statepoint_sourcesep/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/surface_tally/__init__.py b/tests/regression_tests/surface_tally/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/survival_biasing/__init__.py b/tests/regression_tests/survival_biasing/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tallies/__init__.py b/tests/regression_tests/tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tally_aggregation/__init__.py b/tests/regression_tests/tally_aggregation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tally_arithmetic/__init__.py b/tests/regression_tests/tally_arithmetic/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tally_assumesep/__init__.py b/tests/regression_tests/tally_assumesep/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tally_nuclides/__init__.py b/tests/regression_tests/tally_nuclides/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/tally_slice_merge/__init__.py b/tests/regression_tests/tally_slice_merge/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/trace/__init__.py b/tests/regression_tests/trace/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/track_output/__init__.py b/tests/regression_tests/track_output/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/translation/__init__.py b/tests/regression_tests/translation/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/trigger_batch_interval/__init__.py b/tests/regression_tests/trigger_batch_interval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/trigger_no_batch_interval/__init__.py b/tests/regression_tests/trigger_no_batch_interval/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/trigger_no_status/__init__.py b/tests/regression_tests/trigger_no_status/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/trigger_tallies/__init__.py b/tests/regression_tests/trigger_tallies/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/triso/__init__.py b/tests/regression_tests/triso/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/uniform_fs/__init__.py b/tests/regression_tests/uniform_fs/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/universe/__init__.py b/tests/regression_tests/universe/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/void/__init__.py b/tests/regression_tests/void/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/regression_tests/volume_calc/__init__.py b/tests/regression_tests/volume_calc/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 From 72aebfccf262d798e0ae574eb9c3989ec15be285 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 10:52:36 -0600 Subject: [PATCH 049/212] Fix subtle bug with next_id not getting reset for autogenerated IDs --- openmc/mixin.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/openmc/mixin.py b/openmc/mixin.py index d724fc32a0..09a63ae4e4 100644 --- a/openmc/mixin.py +++ b/openmc/mixin.py @@ -45,14 +45,24 @@ class IDManagerMixin(object): @id.setter def id(self, uid): - cls = type(self) - name = cls.__name__ + # The first time this is called for a class, we search through the MRO + # to determine which class actually holds next_id and used_ids. Since + # next_id is an integer (immutable), we can't modify it directly through + # the instance without just creating a new attribute + try: + cls = self._id_class + except AttributeError: + for cls in self.__class__.__mro__: + if 'next_id' in cls.__dict__: + break + if uid is None: while cls.next_id in cls.used_ids: cls.next_id += 1 self._id = cls.next_id cls.used_ids.add(cls.next_id) else: + name = cls.__name__ cv.check_type('{} ID'.format(name), uid, Integral) cv.check_greater_than('{} ID'.format(name), uid, 0, equality=True) if uid in cls.used_ids: From 98d5496102b418613665f5caa7b447cd8ecdaeae Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 10:53:46 -0600 Subject: [PATCH 050/212] Ability to run regression tests using pytest --- pytest.ini | 4 +++ .../asymmetric_lattice/test.py | 11 ++++--- tests/regression_tests/cmfd_feed/test.py | 10 ++----- tests/regression_tests/cmfd_nofeed/test.py | 10 ++----- tests/regression_tests/complex_cell/test.py | 10 ++----- .../confidence_intervals/test.py | 10 ++----- .../create_fission_neutrons/test.py | 11 +++---- tests/regression_tests/density/test.py | 10 ++----- tests/regression_tests/diff_tally/test.py | 12 ++++---- tests/regression_tests/distribmat/test.py | 11 +++---- .../eigenvalue_genperbatch/test.py | 10 ++----- .../eigenvalue_no_inactive/test.py | 10 ++----- tests/regression_tests/energy_cutoff/test.py | 11 +++---- tests/regression_tests/energy_grid/test.py | 10 ++----- tests/regression_tests/energy_laws/test.py | 11 ++----- tests/regression_tests/enrichment/test.py | 5 +--- tests/regression_tests/entropy/test.py | 11 ++++--- .../filter_distribcell/test.py | 11 +++---- .../regression_tests/filter_energyfun/test.py | 15 ++++------ tests/regression_tests/filter_mesh/test.py | 11 +++---- tests/regression_tests/fixed_source/test.py | 16 ++++------ tests/regression_tests/infinite_cell/test.py | 10 ++----- tests/regression_tests/iso_in_lab/test.py | 10 ++----- tests/regression_tests/lattice/test.py | 10 ++----- tests/regression_tests/lattice_hex/test.py | 10 ++----- tests/regression_tests/lattice_mixed/test.py | 10 ++----- .../regression_tests/lattice_multiple/test.py | 10 ++----- tests/regression_tests/mg_basic/test.py | 11 +++---- tests/regression_tests/mg_convert/test.py | 11 +++---- tests/regression_tests/mg_legendre/test.py | 12 +++----- tests/regression_tests/mg_max_order/test.py | 12 +++----- tests/regression_tests/mg_nuclide/test.py | 12 +++----- .../mg_survival_biasing/test.py | 11 +++---- tests/regression_tests/mg_tallies/test.py | 11 +++---- .../mgxs_library_ce_to_mg/test.py | 15 ++++------ .../mgxs_library_condense/test.py | 16 ++++------ .../mgxs_library_distribcell/test.py | 16 ++++------ .../mgxs_library_hdf5/test.py | 17 ++++------- .../mgxs_library_mesh/test.py | 16 ++++------ .../mgxs_library_no_nuclides/test.py | 13 +++----- .../mgxs_library_nuclides/test.py | 13 +++----- tests/regression_tests/multipole/test.py | 10 +++---- tests/regression_tests/output/test.py | 20 +++++-------- .../particle_restart_eigval/test.py | 10 ++----- .../particle_restart_fixed/test.py | 10 ++----- tests/regression_tests/periodic/test.py | 11 +++---- tests/regression_tests/plot/test.py | 11 +++---- tests/regression_tests/ptables_off/test.py | 10 ++----- .../regression_tests/quadric_surfaces/test.py | 10 ++----- .../regression_tests/reflective_plane/test.py | 10 ++----- .../resonance_scattering/test.py | 11 +++---- tests/regression_tests/rotation/test.py | 10 ++----- tests/regression_tests/salphabeta/test.py | 12 +++----- tests/regression_tests/score_current/test.py | 10 ++----- tests/regression_tests/seed/test.py | 10 ++----- tests/regression_tests/source/test.py | 12 +++----- tests/regression_tests/source_file/test.py | 8 ++--- .../sourcepoint_batch/test.py | 23 ++++++-------- .../sourcepoint_latest/test.py | 13 ++++---- .../sourcepoint_restart/test.py | 10 ++----- .../regression_tests/statepoint_batch/test.py | 10 ++----- .../statepoint_restart/test.py | 11 ++++--- .../statepoint_sourcesep/test.py | 16 ++++------ tests/regression_tests/surface_tally/test.py | 11 +++---- .../regression_tests/survival_biasing/test.py | 10 ++----- tests/regression_tests/tallies/test.py | 12 +++----- .../tally_aggregation/test.py | 16 ++++------ .../regression_tests/tally_arithmetic/test.py | 16 ++++------ .../regression_tests/tally_assumesep/test.py | 10 ++----- tests/regression_tests/tally_nuclides/test.py | 10 ++----- .../tally_slice_merge/test.py | 16 ++++------ tests/regression_tests/trace/test.py | 10 ++----- tests/regression_tests/track_output/test.py | 19 +++++------- tests/regression_tests/translation/test.py | 10 ++----- .../trigger_batch_interval/test.py | 10 ++----- .../trigger_no_batch_interval/test.py | 10 ++----- .../trigger_no_status/test.py | 10 ++----- .../regression_tests/trigger_tallies/test.py | 10 ++----- tests/regression_tests/triso/test.py | 13 +++----- tests/regression_tests/uniform_fs/test.py | 10 ++----- tests/regression_tests/universe/test.py | 10 ++----- tests/regression_tests/void/test.py | 10 ++----- tests/regression_tests/volume_calc/test.py | 13 ++++---- tests/testing_harness.py | 30 ++++++++++++------- 84 files changed, 351 insertions(+), 639 deletions(-) create mode 100644 pytest.ini diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000000..d960ba8d25 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +python_files = test*.py +python_classes = NoThanks +filterwarnings = ignore::UserWarning diff --git a/tests/regression_tests/asymmetric_lattice/test.py b/tests/regression_tests/asymmetric_lattice/test.py index f7cbf35c62..8bb2384855 100644 --- a/tests/regression_tests/asymmetric_lattice/test.py +++ b/tests/regression_tests/asymmetric_lattice/test.py @@ -1,13 +1,11 @@ -#!/usr/bin/env python - import os -import sys import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class AsymmetricLatticeTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -90,6 +88,7 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_asymmetric_lattice(request): harness = AsymmetricLatticeTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/cmfd_feed/test.py b/tests/regression_tests/cmfd_feed/test.py index 30e61d03f5..677c58c2a0 100644 --- a/tests/regression_tests/cmfd_feed/test.py +++ b/tests/regression_tests/cmfd_feed/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import CMFDTestHarness +from tests.testing_harness import CMFDTestHarness -if __name__ == '__main__': +def test_cmfd_feed(request): harness = CMFDTestHarness('statepoint.20.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/cmfd_nofeed/test.py b/tests/regression_tests/cmfd_nofeed/test.py index 30e61d03f5..113efc051d 100644 --- a/tests/regression_tests/cmfd_nofeed/test.py +++ b/tests/regression_tests/cmfd_nofeed/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import CMFDTestHarness +from tests.testing_harness import CMFDTestHarness -if __name__ == '__main__': +def test_cmfd_nofeed(request): harness = CMFDTestHarness('statepoint.20.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/complex_cell/test.py b/tests/regression_tests/complex_cell/test.py index 43f8e5ff0f..0e12eccf66 100755 --- a/tests/regression_tests/complex_cell/test.py +++ b/tests/regression_tests/complex_cell/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_complex_cell(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/confidence_intervals/test.py b/tests/regression_tests/confidence_intervals/test.py index 43f8e5ff0f..9d87e596be 100755 --- a/tests/regression_tests/confidence_intervals/test.py +++ b/tests/regression_tests/confidence_intervals/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_confidence_intervals(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/create_fission_neutrons/test.py b/tests/regression_tests/create_fission_neutrons/test.py index 080a0ab0d8..86ff9a29f9 100755 --- a/tests/regression_tests/create_fission_neutrons/test.py +++ b/tests/regression_tests/create_fission_neutrons/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class CreateFissionNeutronsTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -69,6 +65,7 @@ class CreateFissionNeutronsTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_create_fission_neutrons(request): harness = CreateFissionNeutronsTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/density/test.py b/tests/regression_tests/density/test.py index 43f8e5ff0f..8ce3f5898e 100644 --- a/tests/regression_tests/density/test.py +++ b/tests/regression_tests/density/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_density(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/diff_tally/test.py b/tests/regression_tests/diff_tally/test.py index 5f1da9c30a..87dcd77b8f 100644 --- a/tests/regression_tests/diff_tally/test.py +++ b/tests/regression_tests/diff_tally/test.py @@ -1,15 +1,12 @@ -#!/usr/bin/env python - import glob import os -import sys import pandas as pd - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + + class DiffTallyTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): super(DiffTallyTestHarness, self).__init__(*args, **kwargs) @@ -125,6 +122,7 @@ class DiffTallyTestHarness(PyAPITestHarness): return df.to_csv(None, columns=cols, index=False, float_format='%.7e') -if __name__ == '__main__': +def test_diff_tally(request): harness = DiffTallyTestHarness('statepoint.3.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/distribmat/test.py b/tests/regression_tests/distribmat/test.py index d18bb15430..fdb77669ec 100644 --- a/tests/regression_tests/distribmat/test.py +++ b/tests/regression_tests/distribmat/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness, PyAPITestHarness import openmc +from tests.testing_harness import TestHarness, PyAPITestHarness + class DistribmatTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -103,6 +99,7 @@ class DistribmatTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_distribmat(request): harness = DistribmatTestHarness('statepoint.5.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/eigenvalue_genperbatch/test.py b/tests/regression_tests/eigenvalue_genperbatch/test.py index a36c2ae374..1ba8e0d637 100644 --- a/tests/regression_tests/eigenvalue_genperbatch/test.py +++ b/tests/regression_tests/eigenvalue_genperbatch/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_eigenvalue_genperbatch(request): harness = TestHarness('statepoint.7.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/eigenvalue_no_inactive/test.py b/tests/regression_tests/eigenvalue_no_inactive/test.py index 43f8e5ff0f..a7ed17e0d4 100644 --- a/tests/regression_tests/eigenvalue_no_inactive/test.py +++ b/tests/regression_tests/eigenvalue_no_inactive/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_eigenvalue_no_inactive(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/energy_cutoff/test.py b/tests/regression_tests/energy_cutoff/test.py index 74f7b2ab2a..d597b331f2 100755 --- a/tests/regression_tests/energy_cutoff/test.py +++ b/tests/regression_tests/energy_cutoff/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class EnergyCutoffTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -73,6 +69,7 @@ class EnergyCutoffTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_energy_cutoff(request): harness = EnergyCutoffTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/energy_grid/test.py b/tests/regression_tests/energy_grid/test.py index 43f8e5ff0f..f03e7de66a 100644 --- a/tests/regression_tests/energy_grid/test.py +++ b/tests/regression_tests/energy_grid/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_energy_grid(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/energy_laws/test.py b/tests/regression_tests/energy_laws/test.py index 5180344dab..02a58f763b 100644 --- a/tests/regression_tests/energy_laws/test.py +++ b/tests/regression_tests/energy_laws/test.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - """The purpose of this test is to provide coverage of energy distributions that are not covered in other tests. It has a single material with the following nuclides: @@ -18,13 +16,10 @@ that use linear-linear interpolation. """ -import glob -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_energy_laws(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/enrichment/test.py b/tests/regression_tests/enrichment/test.py index 395fafdf56..a20838c7cb 100644 --- a/tests/regression_tests/enrichment/test.py +++ b/tests/regression_tests/enrichment/test.py @@ -1,16 +1,13 @@ -#!/usr/bin/env python - import os import sys import numpy as np -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) from openmc import Material from openmc.data import NATURAL_ABUNDANCE, atomic_mass -if __name__ == '__main__': +def test_enrichment(): # This test doesn't require an OpenMC run. We just need to make sure the # element.expand() method expands Uranium to the proper enrichment. diff --git a/tests/regression_tests/entropy/test.py b/tests/regression_tests/entropy/test.py index bbc6c0c7f4..c2ccceffed 100644 --- a/tests/regression_tests/entropy/test.py +++ b/tests/regression_tests/entropy/test.py @@ -1,12 +1,10 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + from openmc import StatePoint +from tests.testing_harness import TestHarness + class EntropyTestHarness(TestHarness): def _get_results(self): @@ -26,6 +24,7 @@ class EntropyTestHarness(TestHarness): return outstr -if __name__ == '__main__': +def test_entropy(request): harness = EntropyTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/filter_distribcell/test.py b/tests/regression_tests/filter_distribcell/test.py index 320a808a5f..a1354f56f9 100644 --- a/tests/regression_tests/filter_distribcell/test.py +++ b/tests/regression_tests/filter_distribcell/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - import glob -import hashlib import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import * + +from tests.testing_harness import * class DistribcellTestHarness(TestHarness): @@ -72,6 +68,7 @@ class DistribcellTestHarness(TestHarness): 'Tally output file does not exist.' -if __name__ == '__main__': +def test_filter_distribcell(request): harness = DistribcellTestHarness() + harness.request = request harness.main() diff --git a/tests/regression_tests/filter_energyfun/test.py b/tests/regression_tests/filter_energyfun/test.py index 1de522f540..c4d0d60f97 100644 --- a/tests/regression_tests/filter_energyfun/test.py +++ b/tests/regression_tests/filter_energyfun/test.py @@ -1,12 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -import glob -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class FilterEnergyFunHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -38,8 +33,7 @@ class FilterEnergyFunHarness(PyAPITestHarness): def _get_results(self): # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) # Use tally arithmetic to compute the branching ratio. br_tally = sp.tallies[2] / sp.tallies[1] @@ -48,6 +42,7 @@ class FilterEnergyFunHarness(PyAPITestHarness): return br_tally.get_pandas_dataframe().to_string() + '\n' -if __name__ == '__main__': +def test_filter_energyfun(request): harness = FilterEnergyFunHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/filter_mesh/test.py b/tests/regression_tests/filter_mesh/test.py index 4ad5e9005b..e5a0baba1d 100644 --- a/tests/regression_tests/filter_mesh/test.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import HashedPyAPITestHarness import openmc +from tests.testing_harness import HashedPyAPITestHarness + class FilterMeshTestHarness(HashedPyAPITestHarness): def __init__(self, *args, **kwargs): @@ -67,6 +63,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) -if __name__ == '__main__': +def test_filter_mesh(request): harness = FilterMeshTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/fixed_source/test.py b/tests/regression_tests/fixed_source/test.py index 3e28610fb0..caef20a4cb 100644 --- a/tests/regression_tests/fixed_source/test.py +++ b/tests/regression_tests/fixed_source/test.py @@ -1,22 +1,17 @@ -#!/usr/bin/env python - -import glob -import os -import sys import numpy as np -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.stats +from tests.testing_harness import PyAPITestHarness + class FixedSourceTestHarness(PyAPITestHarness): def _get_results(self): """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] outstr = '' - with openmc.StatePoint(statepoint) as sp: + with openmc.StatePoint(self._sp_name) as sp: # Write out tally data. for i, tally_ind in enumerate(sp.tallies): tally = sp.tallies[tally_ind] @@ -36,7 +31,7 @@ class FixedSourceTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_fixed_source(request): mat = openmc.Material() mat.add_nuclide('O16', 1.0) mat.add_nuclide('U238', 0.0001) @@ -61,4 +56,5 @@ if __name__ == '__main__': model.tallies.append(tally) harness = FixedSourceTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/infinite_cell/test.py b/tests/regression_tests/infinite_cell/test.py index 43f8e5ff0f..0e2d8454db 100644 --- a/tests/regression_tests/infinite_cell/test.py +++ b/tests/regression_tests/infinite_cell/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_infinite_cell(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/iso_in_lab/test.py b/tests/regression_tests/iso_in_lab/test.py index 8cc9c7b7d7..37bf05a069 100644 --- a/tests/regression_tests/iso_in_lab/test.py +++ b/tests/regression_tests/iso_in_lab/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': +def test_iso_in_lab(request): # Force iso-in-lab scattering. harness = PyAPITestHarness('statepoint.10.h5') harness._model.materials.make_isotropic_in_lab() + harness.request = request harness.main() diff --git a/tests/regression_tests/lattice/test.py b/tests/regression_tests/lattice/test.py index 43f8e5ff0f..34c598680b 100644 --- a/tests/regression_tests/lattice/test.py +++ b/tests/regression_tests/lattice/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_lattice(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_hex/test.py b/tests/regression_tests/lattice_hex/test.py index 43f8e5ff0f..b0028f3c52 100644 --- a/tests/regression_tests/lattice_hex/test.py +++ b/tests/regression_tests/lattice_hex/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_lattice_hex(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_mixed/test.py b/tests/regression_tests/lattice_mixed/test.py index 43f8e5ff0f..2feb9a1381 100644 --- a/tests/regression_tests/lattice_mixed/test.py +++ b/tests/regression_tests/lattice_mixed/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_lattice_mixed(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_multiple/test.py b/tests/regression_tests/lattice_multiple/test.py index 43f8e5ff0f..15daf0beac 100644 --- a/tests/regression_tests/lattice_multiple/test.py +++ b/tests/regression_tests/lattice_multiple/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_lattice_multiple(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_basic/test.py b/tests/regression_tests/mg_basic/test.py index 054503f9ab..9fb2681ffd 100644 --- a/tests/regression_tests/mg_basic/test.py +++ b/tests/regression_tests/mg_basic/test.py @@ -1,13 +1,10 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_basic(request): model = slab_mg() harness = PyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_convert/test.py b/tests/regression_tests/mg_convert/test.py index 45f701ff11..f51e4e87b9 100755 --- a/tests/regression_tests/mg_convert/test.py +++ b/tests/regression_tests/mg_convert/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - import os -import sys import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) import numpy as np - -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + # OpenMC simulation parameters batches = 10 inactive = 5 @@ -202,6 +198,7 @@ class MGXSTestHarness(PyAPITestHarness): self._cleanup() -if __name__ == '__main__': +def test_mg_convert(request): harness = MGXSTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_legendre/test.py b/tests/regression_tests/mg_legendre/test.py index 2e574afb61..a15cd5f94b 100644 --- a/tests/regression_tests/mg_legendre/test.py +++ b/tests/regression_tests/mg_legendre/test.py @@ -1,16 +1,12 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_legendre(request): model = slab_mg(reps=['iso']) model.settings.tabular_legendre = {'enable': False} harness = PyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_max_order/test.py b/tests/regression_tests/mg_max_order/test.py index 21fd2c0b64..c8f1ee7287 100644 --- a/tests/regression_tests/mg_max_order/test.py +++ b/tests/regression_tests/mg_max_order/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_max_order(request): model = slab_mg(reps=['iso']) model.settings.max_order = 1 harness = PyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_nuclide/test.py b/tests/regression_tests/mg_nuclide/test.py index d1c06cd417..fd298b3680 100644 --- a/tests/regression_tests/mg_nuclide/test.py +++ b/tests/regression_tests/mg_nuclide/test.py @@ -1,14 +1,10 @@ -#!/usr/bin/env python - -import os -import sys - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_nuclide(request): model = slab_mg(as_macro=False) harness = PyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_survival_biasing/test.py b/tests/regression_tests/mg_survival_biasing/test.py index 2669201c0e..a4c6e48097 100644 --- a/tests/regression_tests/mg_survival_biasing/test.py +++ b/tests/regression_tests/mg_survival_biasing/test.py @@ -1,14 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness from openmc.examples import slab_mg +from tests.testing_harness import PyAPITestHarness -if __name__ == '__main__': + +def test_mg_survival_biasing(request): model = slab_mg() model.settings.survival_biasing = True harness = PyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mg_tallies/test.py b/tests/regression_tests/mg_tallies/test.py index ec7081e2ad..2adf34f7a2 100644 --- a/tests/regression_tests/mg_tallies/test.py +++ b/tests/regression_tests/mg_tallies/test.py @@ -1,14 +1,10 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import HashedPyAPITestHarness import openmc from openmc.examples import slab_mg +from tests.testing_harness import HashedPyAPITestHarness -if __name__ == '__main__': + +def test_mg_tallies(request): model = slab_mg(as_macro=False) # Instantiate a tally mesh @@ -92,4 +88,5 @@ if __name__ == '__main__': model.tallies.append(t) harness = HashedPyAPITestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/test.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py index e29cf58313..c8bcef172a 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/test.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -1,14 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -import glob -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -42,8 +37,7 @@ class MGXSTestHarness(PyAPITestHarness): # Build MG Inputs # Get data needed to execute Library calculations. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - sp = openmc.StatePoint(statepoint) + sp = openmc.StatePoint(self._sp_name) self.mgxs_lib.load_from_statepoint(sp) self._model.mgxs_file, self._model.materials, \ self._model.geometry = self.mgxs_lib.create_mg_mode() @@ -80,9 +74,10 @@ class MGXSTestHarness(PyAPITestHarness): os.remove(f) -if __name__ == '__main__': +def test_mgxs_library_ce_to_mg(request): # Set the input set to use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_condense/test.py b/tests/regression_tests/mgxs_library_condense/test.py index fd144636f9..c88c523417 100644 --- a/tests/regression_tests/mgxs_library_condense/test.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -38,8 +34,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -65,8 +60,9 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_condense(request): # Use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_distribcell/test.py b/tests/regression_tests/mgxs_library_distribcell/test.py index e59f4c7578..f18ae54b10 100644 --- a/tests/regression_tests/mgxs_library_distribcell/test.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs from openmc.examples import pwr_assembly +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -43,8 +39,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -69,7 +64,8 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_distribcell(request): model = pwr_assembly() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_hdf5/test.py b/tests/regression_tests/mgxs_library_hdf5/test.py index 8daf828cea..b070f22e82 100644 --- a/tests/regression_tests/mgxs_library_hdf5/test.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -1,19 +1,14 @@ -#!/usr/bin/env python - import os -import sys -import glob import hashlib import numpy as np import h5py - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) @@ -46,8 +41,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -77,12 +71,13 @@ class MGXSTestHarness(PyAPITestHarness): def _cleanup(self): super(MGXSTestHarness, self)._cleanup() - f = os.path.join(os.getcwd(), 'mgxs.h5') + f = 'mgxs.h5' if os.path.exists(f): os.remove(f) -if __name__ == '__main__': +def test_mgxs_library_hdf5(request): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_mesh/test.py b/tests/regression_tests/mgxs_library_mesh/test.py index 06cb10601b..809782467d 100644 --- a/tests/regression_tests/mgxs_library_mesh/test.py +++ b/tests/regression_tests/mgxs_library_mesh/test.py @@ -1,14 +1,10 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -47,8 +43,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) @@ -70,6 +65,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_mesh(request): harness = MGXSTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_no_nuclides/test.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py index ede916059c..743be994fd 100644 --- a/tests/regression_tests/mgxs_library_no_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -39,8 +35,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) diff --git a/tests/regression_tests/mgxs_library_nuclides/test.py b/tests/regression_tests/mgxs_library_nuclides/test.py index e668ab52cc..23ebb23297 100644 --- a/tests/regression_tests/mgxs_library_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -1,15 +1,11 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell +from tests.testing_harness import PyAPITestHarness + class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -35,8 +31,7 @@ class MGXSTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the MGXS library from the statepoint self.mgxs_lib.load_from_statepoint(sp) diff --git a/tests/regression_tests/multipole/test.py b/tests/regression_tests/multipole/test.py index 20da97f7c0..a91bdae5ee 100644 --- a/tests/regression_tests/multipole/test.py +++ b/tests/regression_tests/multipole/test.py @@ -1,11 +1,10 @@ -#!/usr/bin/env python import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness, PyAPITestHarness + import openmc import openmc.model +from tests.testing_harness import TestHarness, PyAPITestHarness + def make_model(): model = openmc.model.Model() @@ -81,7 +80,8 @@ class MultipoleTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_multipole(request): model = make_model() harness = MultipoleTestHarness('statepoint.5.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/output/test.py b/tests/regression_tests/output/test.py index 0092f54919..30fcc3a80c 100644 --- a/tests/regression_tests/output/test.py +++ b/tests/regression_tests/output/test.py @@ -1,10 +1,7 @@ -#!/usr/bin/env python - -import glob import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +import glob + +from tests.testing_harness import TestHarness class OutputTestHarness(TestHarness): @@ -21,13 +18,12 @@ class OutputTestHarness(TestHarness): def _cleanup(self): TestHarness._cleanup(self) - output = glob.glob(os.path.join(os.getcwd(), 'summary.*')) - output.append(os.path.join(os.getcwd(), 'cross_sections.out')) - for f in output: - if os.path.exists(f): - os.remove(f) + f = 'summary.h5' + if os.path.exists(f): + os.remove(f) -if __name__ == '__main__': +def test_output(request): harness = OutputTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/particle_restart_eigval/test.py b/tests/regression_tests/particle_restart_eigval/test.py index 455ff9e927..6b9d103fdb 100644 --- a/tests/regression_tests/particle_restart_eigval/test.py +++ b/tests/regression_tests/particle_restart_eigval/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import ParticleRestartTestHarness +from tests.testing_harness import ParticleRestartTestHarness -if __name__ == '__main__': +def test_particle_restart_eigval(request): harness = ParticleRestartTestHarness('particle_10_1030.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/particle_restart_fixed/test.py b/tests/regression_tests/particle_restart_fixed/test.py index e473fdb59e..428d9586d9 100644 --- a/tests/regression_tests/particle_restart_fixed/test.py +++ b/tests/regression_tests/particle_restart_fixed/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import ParticleRestartTestHarness +from tests.testing_harness import ParticleRestartTestHarness -if __name__ == '__main__': +def test_particle_restart_fixed(request): harness = ParticleRestartTestHarness('particle_7_144.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/periodic/test.py b/tests/regression_tests/periodic/test.py index ddd7cd89b8..188827a5dc 100644 --- a/tests/regression_tests/periodic/test.py +++ b/tests/regression_tests/periodic/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class PeriodicTest(PyAPITestHarness): def _build_inputs(self): @@ -55,6 +51,7 @@ class PeriodicTest(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_periodic(request): harness = PeriodicTest('statepoint.4.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/plot/test.py b/tests/regression_tests/plot/test.py index d0c362ef2b..1e7773ea6a 100644 --- a/tests/regression_tests/plot/test.py +++ b/tests/regression_tests/plot/test.py @@ -1,16 +1,12 @@ -#!/usr/bin/env python - import glob import hashlib import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness import h5py - import openmc +from tests.testing_harness import TestHarness + class PlotTestHarness(TestHarness): """Specialized TestHarness for running OpenMC plotting tests.""" @@ -60,7 +56,8 @@ class PlotTestHarness(TestHarness): return outstr -if __name__ == '__main__': +def test_plot(request): harness = PlotTestHarness(('plot_1.ppm', 'plot_2.ppm', 'plot_3.ppm', 'plot_4.h5')) + harness.request = request harness.main() diff --git a/tests/regression_tests/ptables_off/test.py b/tests/regression_tests/ptables_off/test.py index 43f8e5ff0f..8d67cf400b 100644 --- a/tests/regression_tests/ptables_off/test.py +++ b/tests/regression_tests/ptables_off/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_ptables_off(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/quadric_surfaces/test.py b/tests/regression_tests/quadric_surfaces/test.py index 43f8e5ff0f..f919f1648c 100755 --- a/tests/regression_tests/quadric_surfaces/test.py +++ b/tests/regression_tests/quadric_surfaces/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_quadric_surfaces(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/reflective_plane/test.py b/tests/regression_tests/reflective_plane/test.py index 43f8e5ff0f..ba693c61aa 100644 --- a/tests/regression_tests/reflective_plane/test.py +++ b/tests/regression_tests/reflective_plane/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_reflective_plane(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/resonance_scattering/test.py b/tests/regression_tests/resonance_scattering/test.py index 3ed7fe2272..98096a0cac 100644 --- a/tests/regression_tests/resonance_scattering/test.py +++ b/tests/regression_tests/resonance_scattering/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class ResonanceScatteringTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -46,6 +42,7 @@ class ResonanceScatteringTestHarness(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_resonance_scattering(request): harness = ResonanceScatteringTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/rotation/test.py b/tests/regression_tests/rotation/test.py index 43f8e5ff0f..b27e7faa4b 100644 --- a/tests/regression_tests/rotation/test.py +++ b/tests/regression_tests/rotation/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_rotation(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/salphabeta/test.py b/tests/regression_tests/salphabeta/test.py index 6ced79a8d6..4ab213fce9 100644 --- a/tests/regression_tests/salphabeta/test.py +++ b/tests/regression_tests/salphabeta/test.py @@ -1,13 +1,8 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) - -from testing_harness import PyAPITestHarness import openmc import openmc.model +from tests.testing_harness import PyAPITestHarness + def make_model(): model = openmc.model.Model() @@ -78,7 +73,8 @@ def make_model(): return model -if __name__ == '__main__': +def test_salphabeta(request): model = make_model() harness = PyAPITestHarness('statepoint.5.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/score_current/test.py b/tests/regression_tests/score_current/test.py index 70ddc22198..1acc7c604f 100644 --- a/tests/regression_tests/score_current/test.py +++ b/tests/regression_tests/score_current/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import HashedTestHarness +from tests.testing_harness import HashedTestHarness -if __name__ == '__main__': +def test_score_current(request): harness = HashedTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/seed/test.py b/tests/regression_tests/seed/test.py index 43f8e5ff0f..4c6bf95dc2 100644 --- a/tests/regression_tests/seed/test.py +++ b/tests/regression_tests/seed/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_seed(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/source/test.py b/tests/regression_tests/source/test.py index 7a3d054d8e..aa17143f0d 100644 --- a/tests/regression_tests/source/test.py +++ b/tests/regression_tests/source/test.py @@ -1,15 +1,10 @@ -#!/usr/bin/env python - from math import pi -import os -import sys import numpy as np - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc +from tests.testing_harness import PyAPITestHarness + class SourceTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -63,6 +58,7 @@ class SourceTestHarness(PyAPITestHarness): settings.export_to_xml() -if __name__ == '__main__': +def test_source(request): harness = SourceTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/source_file/test.py b/tests/regression_tests/source_file/test.py index f04441a208..1989de4c90 100644 --- a/tests/regression_tests/source_file/test.py +++ b/tests/regression_tests/source_file/test.py @@ -2,9 +2,8 @@ import glob import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import * + +from tests.testing_harness import * settings1=""" @@ -97,6 +96,7 @@ class SourceFileTestHarness(TestHarness): fh.write(settings1) -if __name__ == '__main__': +def test_source_file(request): harness = SourceFileTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_batch/test.py b/tests/regression_tests/sourcepoint_batch/test.py index 1239a00dcd..96326d15b8 100644 --- a/tests/regression_tests/sourcepoint_batch/test.py +++ b/tests/regression_tests/sourcepoint_batch/test.py @@ -1,20 +1,15 @@ -#!/usr/bin/env python - import glob -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + from openmc import StatePoint +from tests.testing_harness import TestHarness + class SourcepointTestHarness(TestHarness): def _test_output_created(self): - """Make sure statepoint.* files have been created.""" - statepoint = glob.glob(os.path.join(os.getcwd(), 'statepoint.*')) - assert len(statepoint) == 5, '5 statepoint files must exist.' - assert statepoint[0].endswith('h5'), \ - 'Statepoint file is not a HDF5 file.' + """Make sure statepoint files have been created.""" + statepoint = glob.glob('statepoint.*.h5') + assert len(statepoint) == 5, 'Five statepoint files must exist.' def _get_results(self): """Digest info in the statepoint and return as a string.""" @@ -22,8 +17,7 @@ class SourcepointTestHarness(TestHarness): outstr = TestHarness._get_results(self) # Read the statepoint file. - statepoint = glob.glob(os.path.join(os.getcwd(), self._sp_name))[0] - with StatePoint(statepoint) as sp: + with StatePoint(self._sp_name) as sp: # Add the source information. xyz = sp.source[0]['xyz'] outstr += ' '.join(['{0:12.6E}'.format(x) for x in xyz]) @@ -32,6 +26,7 @@ class SourcepointTestHarness(TestHarness): return outstr -if __name__ == '__main__': +def test_sourcepoint_batch(request): harness = SourcepointTestHarness('statepoint.08.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_latest/test.py b/tests/regression_tests/sourcepoint_latest/test.py index 4af176eecd..15082e6d82 100644 --- a/tests/regression_tests/sourcepoint_latest/test.py +++ b/tests/regression_tests/sourcepoint_latest/test.py @@ -1,22 +1,19 @@ -#!/usr/bin/env python - import os import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + +from tests.testing_harness import TestHarness class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) - source = glob.glob(os.path.join(os.getcwd(), 'source.*')) + source = glob.glob(os.path.join(os.getcwd(), 'source.*.h5')) assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' - assert source[0].endswith('h5'), \ - 'Source file is not a HDF5 file.' -if __name__ == '__main__': +def test_sourcepoint_latest(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_restart/test.py b/tests/regression_tests/sourcepoint_restart/test.py index 43f8e5ff0f..b0d2e9069a 100644 --- a/tests/regression_tests/sourcepoint_restart/test.py +++ b/tests/regression_tests/sourcepoint_restart/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_sourcepoint_restart(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_batch/test.py b/tests/regression_tests/statepoint_batch/test.py index 0820aa6f01..aeb91e2a6e 100644 --- a/tests/regression_tests/statepoint_batch/test.py +++ b/tests/regression_tests/statepoint_batch/test.py @@ -1,9 +1,4 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness class StatepointTestHarness(TestHarness): @@ -18,6 +13,7 @@ class StatepointTestHarness(TestHarness): TestHarness._test_output_created(self) -if __name__ == '__main__': +def test_statepoint_batch(request): harness = StatepointTestHarness() + harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_restart/test.py b/tests/regression_tests/statepoint_restart/test.py index f3a52c1cf0..219a8a7ed8 100644 --- a/tests/regression_tests/statepoint_restart/test.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -1,12 +1,10 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + import openmc +from tests.testing_harness import TestHarness + class StatepointRestartTestHarness(TestHarness): def __init__(self, final_sp, restart_sp): @@ -56,7 +54,8 @@ class StatepointRestartTestHarness(TestHarness): openmc.run(openmc_exec=self._opts.exe, restart_file=statepoint) -if __name__ == '__main__': +def test_statepoint_restart(request): harness = StatepointRestartTestHarness('statepoint.10.h5', 'statepoint.07.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_sourcesep/test.py b/tests/regression_tests/statepoint_sourcesep/test.py index 904fa471e8..44a45d406f 100644 --- a/tests/regression_tests/statepoint_sourcesep/test.py +++ b/tests/regression_tests/statepoint_sourcesep/test.py @@ -1,30 +1,26 @@ -#!/usr/bin/env python - import glob import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + +from tests.testing_harness import TestHarness class SourcepointTestHarness(TestHarness): def _test_output_created(self): """Make sure statepoint.* and source* have been created.""" TestHarness._test_output_created(self) - source = glob.glob(os.path.join(os.getcwd(), 'source.*')) + source = glob.glob('source.*.h5') assert len(source) == 1, 'Either multiple or no source files ' \ 'exist.' - assert source[0].endswith('h5'), \ - 'Source file is not a HDF5 file.' def _cleanup(self): TestHarness._cleanup(self) - output = glob.glob(os.path.join(os.getcwd(), 'source.*')) + output = glob.glob('source.*.h5') for f in output: if os.path.exists(f): os.remove(f) -if __name__ == '__main__': +def test_statepoint_sourcesep(request): harness = SourcepointTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/surface_tally/test.py b/tests/regression_tests/surface_tally/test.py index 9729fdf20d..2d499cb293 100644 --- a/tests/regression_tests/surface_tally/test.py +++ b/tests/regression_tests/surface_tally/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import numpy as np import openmc import pandas as pd +from tests.testing_harness import PyAPITestHarness + class SurfaceTallyTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -178,6 +174,7 @@ class SurfaceTallyTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_surface_tally(request): harness = SurfaceTallyTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/survival_biasing/test.py b/tests/regression_tests/survival_biasing/test.py index 43f8e5ff0f..2dc7c86ab1 100644 --- a/tests/regression_tests/survival_biasing/test.py +++ b/tests/regression_tests/survival_biasing/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_survival_biasing(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/tallies/test.py b/tests/regression_tests/tallies/test.py index 693e941af1..25545dd82a 100644 --- a/tests/regression_tests/tallies/test.py +++ b/tests/regression_tests/tallies/test.py @@ -1,16 +1,12 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) - -from testing_harness import HashedPyAPITestHarness from openmc.filter import * from openmc import Mesh, Tally, Tallies +from tests.testing_harness import HashedPyAPITestHarness -if __name__ == '__main__': + +def test_tallies(request): harness = HashedPyAPITestHarness('statepoint.5.h5') + harness.request = request model = harness._model # Set settings explicitly diff --git a/tests/regression_tests/tally_aggregation/test.py b/tests/regression_tests/tally_aggregation/test.py index 62d3a3f041..dfa0266902 100644 --- a/tests/regression_tests/tally_aggregation/test.py +++ b/tests/regression_tests/tally_aggregation/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class TallyAggregationTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -28,8 +24,7 @@ class TallyAggregationTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Extract the tally of interest tally = sp.get_tally(name='distribcell tally') @@ -66,6 +61,7 @@ class TallyAggregationTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_aggregation(request): harness = TallyAggregationTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/tally_arithmetic/test.py b/tests/regression_tests/tally_arithmetic/test.py index fab1b0fb2c..c87d0149f4 100644 --- a/tests/regression_tests/tally_arithmetic/test.py +++ b/tests/regression_tests/tally_arithmetic/test.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python - -import os -import sys -import glob import hashlib -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class TallyArithmeticTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -43,8 +39,7 @@ class TallyArithmeticTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Load the tallies tally_1 = sp.get_tally(name='tally 1') @@ -80,6 +75,7 @@ class TallyArithmeticTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_arithmetic(request): harness = TallyArithmeticTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/tally_assumesep/test.py b/tests/regression_tests/tally_assumesep/test.py index 43f8e5ff0f..c4248c10af 100644 --- a/tests/regression_tests/tally_assumesep/test.py +++ b/tests/regression_tests/tally_assumesep/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_tally_assumesep(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/tally_nuclides/test.py b/tests/regression_tests/tally_nuclides/test.py index 43f8e5ff0f..7eec5ef3f1 100644 --- a/tests/regression_tests/tally_nuclides/test.py +++ b/tests/regression_tests/tally_nuclides/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_tally_nuclides(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/tally_slice_merge/test.py b/tests/regression_tests/tally_slice_merge/test.py index 84908b5cbe..4ee99d34a8 100644 --- a/tests/regression_tests/tally_slice_merge/test.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -1,16 +1,12 @@ -#!/usr/bin/env python - from __future__ import division -import os -import sys -import glob import hashlib import itertools -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class TallySliceMergeTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): @@ -85,8 +81,7 @@ class TallySliceMergeTestHarness(PyAPITestHarness): """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) + sp = openmc.StatePoint(self._sp_name) # Extract the cell tally tallies = [sp.get_tally(name='cell tally')] @@ -171,6 +166,7 @@ class TallySliceMergeTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_tally_slice_merge(request): harness = TallySliceMergeTestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/trace/test.py b/tests/regression_tests/trace/test.py index 43f8e5ff0f..c037bb23bf 100644 --- a/tests/regression_tests/trace/test.py +++ b/tests/regression_tests/trace/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_trace(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/track_output/test.py b/tests/regression_tests/track_output/test.py index c7a2df4ebe..b0abb7ecc8 100644 --- a/tests/regression_tests/track_output/test.py +++ b/tests/regression_tests/track_output/test.py @@ -1,12 +1,11 @@ -#!/usr/bin/env python - import glob import os from subprocess import call import shutil -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness + +import pytest + +from tests.testing_harness import TestHarness class TrackTestHarness(TestHarness): @@ -39,14 +38,10 @@ class TrackTestHarness(TestHarness): os.remove(f) -if __name__ == '__main__': +def test_track_output(request): # If vtk python module is not available, we can't run track.py so skip this # test. - try: - import vtk - except ImportError: - print('----------------Skipping test-------------') - shutil.copy('results_true.dat', 'results_test.dat') - exit() + vtk = pytest.importerskip('vtk') harness = TrackTestHarness('statepoint.2.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/translation/test.py b/tests/regression_tests/translation/test.py index 43f8e5ff0f..29ef1c0114 100644 --- a/tests/regression_tests/translation/test.py +++ b/tests/regression_tests/translation/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_translation(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_batch_interval/test.py b/tests/regression_tests/trigger_batch_interval/test.py index 542c2ffdeb..1ac01a08bf 100644 --- a/tests/regression_tests/trigger_batch_interval/test.py +++ b/tests/regression_tests/trigger_batch_interval/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_trigger_batch_interval(request): harness = TestHarness('statepoint.15.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_no_batch_interval/test.py b/tests/regression_tests/trigger_no_batch_interval/test.py index 542c2ffdeb..d38304feea 100644 --- a/tests/regression_tests/trigger_no_batch_interval/test.py +++ b/tests/regression_tests/trigger_no_batch_interval/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_trigger_no_batch_interval(request): harness = TestHarness('statepoint.15.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_no_status/test.py b/tests/regression_tests/trigger_no_status/test.py index 43f8e5ff0f..98173f8dda 100644 --- a/tests/regression_tests/trigger_no_status/test.py +++ b/tests/regression_tests/trigger_no_status/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_trigger_no_status(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_tallies/test.py b/tests/regression_tests/trigger_tallies/test.py index 542c2ffdeb..fde7298ffe 100644 --- a/tests/regression_tests/trigger_tallies/test.py +++ b/tests/regression_tests/trigger_tallies/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_trigger_tallies(request): harness = TestHarness('statepoint.15.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/triso/test.py b/tests/regression_tests/triso/test.py index c92495ace3..2da26d1d38 100644 --- a/tests/regression_tests/triso/test.py +++ b/tests/regression_tests/triso/test.py @@ -1,18 +1,12 @@ -#!/usr/bin/env python - -import os -import sys -import glob import random from math import sqrt import numpy as np - -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness import openmc import openmc.model +from tests.testing_harness import PyAPITestHarness + class TRISOTestHarness(PyAPITestHarness): def _build_inputs(self): @@ -96,6 +90,7 @@ class TRISOTestHarness(PyAPITestHarness): mats.export_to_xml() -if __name__ == '__main__': +def test_triso(request): harness = TRISOTestHarness('statepoint.5.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/uniform_fs/test.py b/tests/regression_tests/uniform_fs/test.py index 43f8e5ff0f..553484e0ab 100644 --- a/tests/regression_tests/uniform_fs/test.py +++ b/tests/regression_tests/uniform_fs/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_uniform_fs(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/universe/test.py b/tests/regression_tests/universe/test.py index 43f8e5ff0f..5da34d90c8 100644 --- a/tests/regression_tests/universe/test.py +++ b/tests/regression_tests/universe/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_universe(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/void/test.py b/tests/regression_tests/void/test.py index 43f8e5ff0f..a08813c45b 100644 --- a/tests/regression_tests/void/test.py +++ b/tests/regression_tests/void/test.py @@ -1,11 +1,7 @@ -#!/usr/bin/env python - -import os -import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import TestHarness +from tests.testing_harness import TestHarness -if __name__ == '__main__': +def test_void(request): harness = TestHarness('statepoint.10.h5') + harness.request = request harness.main() diff --git a/tests/regression_tests/volume_calc/test.py b/tests/regression_tests/volume_calc/test.py index 47ce27a122..da3a66c36f 100644 --- a/tests/regression_tests/volume_calc/test.py +++ b/tests/regression_tests/volume_calc/test.py @@ -1,12 +1,11 @@ -#!/usr/bin/env python - import os import glob import sys -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) -from testing_harness import PyAPITestHarness + import openmc +from tests.testing_harness import PyAPITestHarness + class VolumeTest(PyAPITestHarness): def _build_inputs(self): @@ -57,8 +56,7 @@ class VolumeTest(PyAPITestHarness): def _get_results(self): outstr = '' - for i, filename in enumerate(sorted(glob.glob(os.path.join( - os.getcwd(), 'volume_*.h5')))): + for i, filename in enumerate(sorted(glob.glob('volume_*.h5'))): outstr += 'Volume calculation {}\n'.format(i) # Read volume calculation results @@ -75,6 +73,7 @@ class VolumeTest(PyAPITestHarness): def _test_output_created(self): pass -if __name__ == '__main__': +def test_volume_calc(request): harness = VolumeTest('') + harness.request = request harness.main() diff --git a/tests/testing_harness.py b/tests/testing_harness.py index ad3b8ac1ec..9aee4f741a 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -11,7 +11,6 @@ import sys import numpy as np -sys.path.insert(0, os.path.join(os.pardir, os.pardir)) import openmc from openmc.examples import pwr_core @@ -33,10 +32,14 @@ class TestHarness(object): def main(self): """Accept commandline arguments and either run or update tests.""" (self._opts, self._args) = self.parser.parse_args() - if self._opts.update: - self.update_results() - else: - self.execute_test() + try: + olddir = self.request.fspath.dirpath().chdir() + if self._opts.update: + self.update_results() + else: + self.execute_test() + finally: + olddir.chdir() def execute_test(self): """Run OpenMC with the appropriate arguments and check the outputs.""" @@ -234,6 +237,7 @@ class PyAPITestHarness(TestHarness): super(PyAPITestHarness, self).__init__(statepoint_name) self.parser.add_option('-b', '--build-inputs', dest='build_only', action='store_true', default=False) + openmc.reset_auto_ids() if model is None: self._model = pwr_core() else: @@ -244,12 +248,16 @@ class PyAPITestHarness(TestHarness): def main(self): """Accept commandline arguments and either run or update tests.""" (self._opts, self._args) = self.parser.parse_args() - if self._opts.build_only: - self._build_inputs() - elif self._opts.update: - self.update_results() - else: - self.execute_test() + try: + olddir = self.request.fspath.dirpath().chdir() + if self._opts.build_only: + self._build_inputs() + elif self._opts.update: + self.update_results() + else: + self.execute_test() + finally: + olddir.chdir() def execute_test(self): """Build input XMLs, run OpenMC, and verify correct results.""" From 73947ad7de5061d094f12a7feebb7e55ca876f31 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 11:39:37 -0600 Subject: [PATCH 051/212] Reset IDs for tests that instantiate models directly --- tests/regression_tests/fixed_source/test.py | 2 +- tests/regression_tests/mg_basic/test.py | 2 +- tests/regression_tests/mg_legendre/test.py | 2 +- tests/regression_tests/mg_max_order/test.py | 2 +- tests/regression_tests/mg_nuclide/test.py | 2 +- .../mg_survival_biasing/test.py | 2 +- tests/regression_tests/mg_tallies/test.py | 2 +- .../mgxs_library_ce_to_mg/test.py | 10 ++++++---- .../mgxs_library_condense/test.py | 2 +- .../mgxs_library_distribcell/test.py | 2 +- .../regression_tests/mgxs_library_hdf5/test.py | 17 +++++++++-------- .../mgxs_library_no_nuclides/test.py | 3 ++- .../mgxs_library_nuclides/test.py | 3 ++- tests/regression_tests/multipole/test.py | 2 +- tests/regression_tests/salphabeta/test.py | 2 +- tests/regression_tests/tallies/test.py | 2 +- tests/regression_tests/track_output/test.py | 2 +- 17 files changed, 32 insertions(+), 27 deletions(-) diff --git a/tests/regression_tests/fixed_source/test.py b/tests/regression_tests/fixed_source/test.py index caef20a4cb..e652ed3f82 100644 --- a/tests/regression_tests/fixed_source/test.py +++ b/tests/regression_tests/fixed_source/test.py @@ -31,7 +31,7 @@ class FixedSourceTestHarness(PyAPITestHarness): return outstr -def test_fixed_source(request): +def test_fixed_source(request, reset_ids): mat = openmc.Material() mat.add_nuclide('O16', 1.0) mat.add_nuclide('U238', 0.0001) diff --git a/tests/regression_tests/mg_basic/test.py b/tests/regression_tests/mg_basic/test.py index 9fb2681ffd..7b4ec247a6 100644 --- a/tests/regression_tests/mg_basic/test.py +++ b/tests/regression_tests/mg_basic/test.py @@ -3,7 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_basic(request): +def test_mg_basic(request, reset_ids): model = slab_mg() harness = PyAPITestHarness('statepoint.10.h5', model) harness.request = request diff --git a/tests/regression_tests/mg_legendre/test.py b/tests/regression_tests/mg_legendre/test.py index a15cd5f94b..58ea4a1dc4 100644 --- a/tests/regression_tests/mg_legendre/test.py +++ b/tests/regression_tests/mg_legendre/test.py @@ -3,7 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_legendre(request): +def test_mg_legendre(request, reset_ids): model = slab_mg(reps=['iso']) model.settings.tabular_legendre = {'enable': False} diff --git a/tests/regression_tests/mg_max_order/test.py b/tests/regression_tests/mg_max_order/test.py index c8f1ee7287..72bca32317 100644 --- a/tests/regression_tests/mg_max_order/test.py +++ b/tests/regression_tests/mg_max_order/test.py @@ -3,7 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_max_order(request): +def test_mg_max_order(request, reset_ids): model = slab_mg(reps=['iso']) model.settings.max_order = 1 harness = PyAPITestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mg_nuclide/test.py b/tests/regression_tests/mg_nuclide/test.py index fd298b3680..53eac5e8d5 100644 --- a/tests/regression_tests/mg_nuclide/test.py +++ b/tests/regression_tests/mg_nuclide/test.py @@ -3,7 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_nuclide(request): +def test_mg_nuclide(request, reset_ids): model = slab_mg(as_macro=False) harness = PyAPITestHarness('statepoint.10.h5', model) harness.request = request diff --git a/tests/regression_tests/mg_survival_biasing/test.py b/tests/regression_tests/mg_survival_biasing/test.py index a4c6e48097..09a210d046 100644 --- a/tests/regression_tests/mg_survival_biasing/test.py +++ b/tests/regression_tests/mg_survival_biasing/test.py @@ -3,7 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_survival_biasing(request): +def test_mg_survival_biasing(request, reset_ids): model = slab_mg() model.settings.survival_biasing = True harness = PyAPITestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mg_tallies/test.py b/tests/regression_tests/mg_tallies/test.py index 2adf34f7a2..3f9bcae79f 100644 --- a/tests/regression_tests/mg_tallies/test.py +++ b/tests/regression_tests/mg_tallies/test.py @@ -4,7 +4,7 @@ from openmc.examples import slab_mg from tests.testing_harness import HashedPyAPITestHarness -def test_mg_tallies(request): +def test_mg_tallies(request, reset_ids): model = slab_mg(as_macro=False) # Instantiate a tally mesh diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/test.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py index c8bcef172a..9246694ea9 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/test.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -1,3 +1,5 @@ +import os + import openmc import openmc.mgxs from openmc.examples import pwr_pin_cell @@ -52,8 +54,8 @@ class MGXSTestHarness(PyAPITestHarness): self._model.materials.export_to_xml() self._model.mgxs_file.export_to_hdf5() # Dont need tallies.xml, so remove the file - if os.path.exists('./tallies.xml'): - os.remove('./tallies.xml') + if os.path.exists('tallies.xml'): + os.remove('tallies.xml') # Enforce closing statepoint and summary files so HDF5 # does not throw an error during the next OpenMC execution @@ -69,12 +71,12 @@ class MGXSTestHarness(PyAPITestHarness): def _cleanup(self): super(MGXSTestHarness, self)._cleanup() - f = os.path.join(os.getcwd(), 'mgxs.h5') + f = 'mgxs.h5' if os.path.exists(f): os.remove(f) -def test_mgxs_library_ce_to_mg(request): +def test_mgxs_library_ce_to_mg(request, reset_ids): # Set the input set to use the pincell model model = pwr_pin_cell() diff --git a/tests/regression_tests/mgxs_library_condense/test.py b/tests/regression_tests/mgxs_library_condense/test.py index c88c523417..b7ecf8925c 100644 --- a/tests/regression_tests/mgxs_library_condense/test.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -60,7 +60,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_condense(request): +def test_mgxs_library_condense(request, reset_ids): # Use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) diff --git a/tests/regression_tests/mgxs_library_distribcell/test.py b/tests/regression_tests/mgxs_library_distribcell/test.py index f18ae54b10..b9f343eafa 100644 --- a/tests/regression_tests/mgxs_library_distribcell/test.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -64,7 +64,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_distribcell(request): +def test_mgxs_library_distribcell(request, reset_ids): model = pwr_assembly() harness = MGXSTestHarness('statepoint.10.h5', model) harness.request = request diff --git a/tests/regression_tests/mgxs_library_hdf5/test.py b/tests/regression_tests/mgxs_library_hdf5/test.py index b070f22e82..38dbeef1a5 100644 --- a/tests/regression_tests/mgxs_library_hdf5/test.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -10,9 +10,6 @@ from openmc.examples import pwr_pin_cell from tests.testing_harness import PyAPITestHarness -np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) - - class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine @@ -76,8 +73,12 @@ class MGXSTestHarness(PyAPITestHarness): os.remove(f) -def test_mgxs_library_hdf5(request): - model = pwr_pin_cell() - harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request - harness.main() +def test_mgxs_library_hdf5(request, reset_ids): + try: + np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) + model = pwr_pin_cell() + harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request + harness.main() + finally: + np.set_printoptions(formatter=None) diff --git a/tests/regression_tests/mgxs_library_no_nuclides/test.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py index 743be994fd..3e6e236480 100644 --- a/tests/regression_tests/mgxs_library_no_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -57,7 +57,8 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_no_nuclides(request, reset_ids): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_nuclides/test.py b/tests/regression_tests/mgxs_library_nuclides/test.py index 23ebb23297..c670e18e30 100644 --- a/tests/regression_tests/mgxs_library_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -53,7 +53,8 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -if __name__ == '__main__': +def test_mgxs_library_nuclides(request, reset_ids): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) + harness.request = request harness.main() diff --git a/tests/regression_tests/multipole/test.py b/tests/regression_tests/multipole/test.py index a91bdae5ee..d7ed3ca7c0 100644 --- a/tests/regression_tests/multipole/test.py +++ b/tests/regression_tests/multipole/test.py @@ -80,7 +80,7 @@ class MultipoleTestHarness(PyAPITestHarness): return outstr -def test_multipole(request): +def test_multipole(request, reset_ids): model = make_model() harness = MultipoleTestHarness('statepoint.5.h5', model) harness.request = request diff --git a/tests/regression_tests/salphabeta/test.py b/tests/regression_tests/salphabeta/test.py index 4ab213fce9..62ccbb2267 100644 --- a/tests/regression_tests/salphabeta/test.py +++ b/tests/regression_tests/salphabeta/test.py @@ -73,7 +73,7 @@ def make_model(): return model -def test_salphabeta(request): +def test_salphabeta(request, reset_ids): model = make_model() harness = PyAPITestHarness('statepoint.5.h5', model) harness.request = request diff --git a/tests/regression_tests/tallies/test.py b/tests/regression_tests/tallies/test.py index 25545dd82a..3f6f7de748 100644 --- a/tests/regression_tests/tallies/test.py +++ b/tests/regression_tests/tallies/test.py @@ -4,7 +4,7 @@ from openmc import Mesh, Tally, Tallies from tests.testing_harness import HashedPyAPITestHarness -def test_tallies(request): +def test_tallies(request, reset_ids): harness = HashedPyAPITestHarness('statepoint.5.h5') harness.request = request model = harness._model diff --git a/tests/regression_tests/track_output/test.py b/tests/regression_tests/track_output/test.py index b0abb7ecc8..f3d665e11e 100644 --- a/tests/regression_tests/track_output/test.py +++ b/tests/regression_tests/track_output/test.py @@ -41,7 +41,7 @@ class TrackTestHarness(TestHarness): def test_track_output(request): # If vtk python module is not available, we can't run track.py so skip this # test. - vtk = pytest.importerskip('vtk') + vtk = pytest.importorskip('vtk') harness = TrackTestHarness('statepoint.2.h5') harness.request = request harness.main() From 740f03fce15760433a90835c2197cb5bc42f5160 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 12:10:24 -0600 Subject: [PATCH 052/212] Use single package-level fixture for regression tests --- .../asymmetric_lattice/test.py | 3 +- tests/regression_tests/cmfd_feed/test.py | 3 +- tests/regression_tests/cmfd_nofeed/test.py | 3 +- tests/regression_tests/complex_cell/test.py | 3 +- .../confidence_intervals/test.py | 3 +- tests/regression_tests/conftest.py | 15 ++++++++++ .../create_fission_neutrons/test.py | 3 +- tests/regression_tests/density/test.py | 3 +- tests/regression_tests/diff_tally/test.py | 3 +- tests/regression_tests/distribmat/test.py | 3 +- .../eigenvalue_genperbatch/test.py | 3 +- .../eigenvalue_no_inactive/test.py | 3 +- tests/regression_tests/energy_cutoff/test.py | 3 +- tests/regression_tests/energy_grid/test.py | 3 +- tests/regression_tests/energy_laws/test.py | 3 +- tests/regression_tests/entropy/test.py | 3 +- .../filter_distribcell/test.py | 3 +- .../regression_tests/filter_energyfun/test.py | 3 +- tests/regression_tests/filter_mesh/test.py | 3 +- tests/regression_tests/fixed_source/test.py | 3 +- tests/regression_tests/infinite_cell/test.py | 3 +- tests/regression_tests/iso_in_lab/test.py | 3 +- tests/regression_tests/lattice/test.py | 3 +- tests/regression_tests/lattice_hex/test.py | 3 +- tests/regression_tests/lattice_mixed/test.py | 3 +- .../regression_tests/lattice_multiple/test.py | 3 +- tests/regression_tests/mg_basic/test.py | 3 +- tests/regression_tests/mg_convert/test.py | 3 +- tests/regression_tests/mg_legendre/test.py | 3 +- tests/regression_tests/mg_max_order/test.py | 3 +- tests/regression_tests/mg_nuclide/test.py | 3 +- .../mg_survival_biasing/test.py | 3 +- tests/regression_tests/mg_tallies/test.py | 3 +- .../mgxs_library_ce_to_mg/test.py | 3 +- .../mgxs_library_condense/test.py | 3 +- .../mgxs_library_distribcell/test.py | 3 +- .../mgxs_library_hdf5/test.py | 3 +- .../mgxs_library_mesh/test.py | 3 +- .../mgxs_library_no_nuclides/test.py | 3 +- .../mgxs_library_nuclides/test.py | 3 +- tests/regression_tests/multipole/test.py | 3 +- tests/regression_tests/output/test.py | 3 +- .../particle_restart_eigval/test.py | 3 +- .../particle_restart_fixed/test.py | 3 +- tests/regression_tests/periodic/test.py | 3 +- tests/regression_tests/plot/test.py | 3 +- tests/regression_tests/ptables_off/test.py | 3 +- .../regression_tests/quadric_surfaces/test.py | 3 +- .../regression_tests/reflective_plane/test.py | 3 +- .../resonance_scattering/test.py | 3 +- tests/regression_tests/rotation/test.py | 3 +- tests/regression_tests/salphabeta/test.py | 3 +- tests/regression_tests/score_current/test.py | 3 +- tests/regression_tests/seed/test.py | 3 +- tests/regression_tests/source/test.py | 3 +- tests/regression_tests/source_file/test.py | 3 +- .../sourcepoint_batch/test.py | 3 +- .../sourcepoint_latest/test.py | 3 +- .../sourcepoint_restart/test.py | 3 +- .../regression_tests/statepoint_batch/test.py | 3 +- .../statepoint_restart/test.py | 3 +- .../statepoint_sourcesep/test.py | 3 +- tests/regression_tests/surface_tally/test.py | 3 +- .../regression_tests/survival_biasing/test.py | 3 +- tests/regression_tests/tallies/test.py | 3 +- .../tally_aggregation/test.py | 3 +- .../regression_tests/tally_arithmetic/test.py | 3 +- .../regression_tests/tally_assumesep/test.py | 3 +- tests/regression_tests/tally_nuclides/test.py | 3 +- .../tally_slice_merge/test.py | 3 +- tests/regression_tests/trace/test.py | 3 +- tests/regression_tests/track_output/test.py | 3 +- tests/regression_tests/translation/test.py | 3 +- .../trigger_batch_interval/test.py | 3 +- .../trigger_no_batch_interval/test.py | 3 +- .../trigger_no_status/test.py | 3 +- .../regression_tests/trigger_tallies/test.py | 3 +- tests/regression_tests/triso/test.py | 3 +- tests/regression_tests/uniform_fs/test.py | 3 +- tests/regression_tests/universe/test.py | 3 +- tests/regression_tests/void/test.py | 3 +- tests/regression_tests/volume_calc/test.py | 3 +- tests/testing_harness.py | 29 +++++++------------ 83 files changed, 106 insertions(+), 181 deletions(-) create mode 100644 tests/regression_tests/conftest.py diff --git a/tests/regression_tests/asymmetric_lattice/test.py b/tests/regression_tests/asymmetric_lattice/test.py index 8bb2384855..0318d7b922 100644 --- a/tests/regression_tests/asymmetric_lattice/test.py +++ b/tests/regression_tests/asymmetric_lattice/test.py @@ -88,7 +88,6 @@ class AsymmetricLatticeTestHarness(PyAPITestHarness): return outstr -def test_asymmetric_lattice(request): +def test_asymmetric_lattice(): harness = AsymmetricLatticeTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/cmfd_feed/test.py b/tests/regression_tests/cmfd_feed/test.py index 677c58c2a0..4fc39d96ad 100644 --- a/tests/regression_tests/cmfd_feed/test.py +++ b/tests/regression_tests/cmfd_feed/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import CMFDTestHarness -def test_cmfd_feed(request): +def test_cmfd_feed(): harness = CMFDTestHarness('statepoint.20.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/cmfd_nofeed/test.py b/tests/regression_tests/cmfd_nofeed/test.py index 113efc051d..a3c7301738 100644 --- a/tests/regression_tests/cmfd_nofeed/test.py +++ b/tests/regression_tests/cmfd_nofeed/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import CMFDTestHarness -def test_cmfd_nofeed(request): +def test_cmfd_nofeed(): harness = CMFDTestHarness('statepoint.20.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/complex_cell/test.py b/tests/regression_tests/complex_cell/test.py index 0e12eccf66..77cbd6cb7d 100755 --- a/tests/regression_tests/complex_cell/test.py +++ b/tests/regression_tests/complex_cell/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_complex_cell(request): +def test_complex_cell(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/confidence_intervals/test.py b/tests/regression_tests/confidence_intervals/test.py index 9d87e596be..3227418280 100755 --- a/tests/regression_tests/confidence_intervals/test.py +++ b/tests/regression_tests/confidence_intervals/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_confidence_intervals(request): +def test_confidence_intervals(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/conftest.py b/tests/regression_tests/conftest.py new file mode 100644 index 0000000000..00ef247dc4 --- /dev/null +++ b/tests/regression_tests/conftest.py @@ -0,0 +1,15 @@ +import openmc +import pytest + + +@pytest.fixture(scope='module', autouse=True) +def setup_regression_test(request): + # Reset autogenerated IDs assigned to OpenMC objects + openmc.reset_auto_ids() + + # Change to test directory + olddir = request.fspath.dirpath().chdir() + try: + yield + finally: + olddir.chdir() diff --git a/tests/regression_tests/create_fission_neutrons/test.py b/tests/regression_tests/create_fission_neutrons/test.py index 86ff9a29f9..f1c1d072cb 100755 --- a/tests/regression_tests/create_fission_neutrons/test.py +++ b/tests/regression_tests/create_fission_neutrons/test.py @@ -65,7 +65,6 @@ class CreateFissionNeutronsTestHarness(PyAPITestHarness): return outstr -def test_create_fission_neutrons(request): +def test_create_fission_neutrons(): harness = CreateFissionNeutronsTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/density/test.py b/tests/regression_tests/density/test.py index 8ce3f5898e..f3ae6b4144 100644 --- a/tests/regression_tests/density/test.py +++ b/tests/regression_tests/density/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_density(request): +def test_density(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/diff_tally/test.py b/tests/regression_tests/diff_tally/test.py index 87dcd77b8f..e383b726e8 100644 --- a/tests/regression_tests/diff_tally/test.py +++ b/tests/regression_tests/diff_tally/test.py @@ -122,7 +122,6 @@ class DiffTallyTestHarness(PyAPITestHarness): return df.to_csv(None, columns=cols, index=False, float_format='%.7e') -def test_diff_tally(request): +def test_diff_tally(): harness = DiffTallyTestHarness('statepoint.3.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/distribmat/test.py b/tests/regression_tests/distribmat/test.py index fdb77669ec..69bb7a67b1 100644 --- a/tests/regression_tests/distribmat/test.py +++ b/tests/regression_tests/distribmat/test.py @@ -99,7 +99,6 @@ class DistribmatTestHarness(PyAPITestHarness): return outstr -def test_distribmat(request): +def test_distribmat(): harness = DistribmatTestHarness('statepoint.5.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/eigenvalue_genperbatch/test.py b/tests/regression_tests/eigenvalue_genperbatch/test.py index 1ba8e0d637..0dfb112428 100644 --- a/tests/regression_tests/eigenvalue_genperbatch/test.py +++ b/tests/regression_tests/eigenvalue_genperbatch/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_eigenvalue_genperbatch(request): +def test_eigenvalue_genperbatch(): harness = TestHarness('statepoint.7.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/eigenvalue_no_inactive/test.py b/tests/regression_tests/eigenvalue_no_inactive/test.py index a7ed17e0d4..5ab4900153 100644 --- a/tests/regression_tests/eigenvalue_no_inactive/test.py +++ b/tests/regression_tests/eigenvalue_no_inactive/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_eigenvalue_no_inactive(request): +def test_eigenvalue_no_inactive(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/energy_cutoff/test.py b/tests/regression_tests/energy_cutoff/test.py index d597b331f2..8b16149947 100755 --- a/tests/regression_tests/energy_cutoff/test.py +++ b/tests/regression_tests/energy_cutoff/test.py @@ -69,7 +69,6 @@ class EnergyCutoffTestHarness(PyAPITestHarness): return outstr -def test_energy_cutoff(request): +def test_energy_cutoff(): harness = EnergyCutoffTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/energy_grid/test.py b/tests/regression_tests/energy_grid/test.py index f03e7de66a..889bdfbc61 100644 --- a/tests/regression_tests/energy_grid/test.py +++ b/tests/regression_tests/energy_grid/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_energy_grid(request): +def test_energy_grid(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/energy_laws/test.py b/tests/regression_tests/energy_laws/test.py index 02a58f763b..8f9bbde356 100644 --- a/tests/regression_tests/energy_laws/test.py +++ b/tests/regression_tests/energy_laws/test.py @@ -19,7 +19,6 @@ that use linear-linear interpolation. from tests.testing_harness import TestHarness -def test_energy_laws(request): +def test_energy_laws(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/entropy/test.py b/tests/regression_tests/entropy/test.py index c2ccceffed..0f1052b6b8 100644 --- a/tests/regression_tests/entropy/test.py +++ b/tests/regression_tests/entropy/test.py @@ -24,7 +24,6 @@ class EntropyTestHarness(TestHarness): return outstr -def test_entropy(request): +def test_entropy(): harness = EntropyTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/filter_distribcell/test.py b/tests/regression_tests/filter_distribcell/test.py index a1354f56f9..bdd134bf57 100644 --- a/tests/regression_tests/filter_distribcell/test.py +++ b/tests/regression_tests/filter_distribcell/test.py @@ -68,7 +68,6 @@ class DistribcellTestHarness(TestHarness): 'Tally output file does not exist.' -def test_filter_distribcell(request): +def test_filter_distribcell(): harness = DistribcellTestHarness() - harness.request = request harness.main() diff --git a/tests/regression_tests/filter_energyfun/test.py b/tests/regression_tests/filter_energyfun/test.py index c4d0d60f97..d9148dd35d 100644 --- a/tests/regression_tests/filter_energyfun/test.py +++ b/tests/regression_tests/filter_energyfun/test.py @@ -42,7 +42,6 @@ class FilterEnergyFunHarness(PyAPITestHarness): return br_tally.get_pandas_dataframe().to_string() + '\n' -def test_filter_energyfun(request): +def test_filter_energyfun(): harness = FilterEnergyFunHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/filter_mesh/test.py b/tests/regression_tests/filter_mesh/test.py index e5a0baba1d..66cd1ac19f 100644 --- a/tests/regression_tests/filter_mesh/test.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -63,7 +63,6 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) -def test_filter_mesh(request): +def test_filter_mesh(): harness = FilterMeshTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/fixed_source/test.py b/tests/regression_tests/fixed_source/test.py index e652ed3f82..7d98de9fc3 100644 --- a/tests/regression_tests/fixed_source/test.py +++ b/tests/regression_tests/fixed_source/test.py @@ -31,7 +31,7 @@ class FixedSourceTestHarness(PyAPITestHarness): return outstr -def test_fixed_source(request, reset_ids): +def test_fixed_source(): mat = openmc.Material() mat.add_nuclide('O16', 1.0) mat.add_nuclide('U238', 0.0001) @@ -56,5 +56,4 @@ def test_fixed_source(request, reset_ids): model.tallies.append(tally) harness = FixedSourceTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/infinite_cell/test.py b/tests/regression_tests/infinite_cell/test.py index 0e2d8454db..59abec3003 100644 --- a/tests/regression_tests/infinite_cell/test.py +++ b/tests/regression_tests/infinite_cell/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_infinite_cell(request): +def test_infinite_cell(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/iso_in_lab/test.py b/tests/regression_tests/iso_in_lab/test.py index 37bf05a069..0e8edc2186 100644 --- a/tests/regression_tests/iso_in_lab/test.py +++ b/tests/regression_tests/iso_in_lab/test.py @@ -1,9 +1,8 @@ from tests.testing_harness import PyAPITestHarness -def test_iso_in_lab(request): +def test_iso_in_lab(): # Force iso-in-lab scattering. harness = PyAPITestHarness('statepoint.10.h5') harness._model.materials.make_isotropic_in_lab() - harness.request = request harness.main() diff --git a/tests/regression_tests/lattice/test.py b/tests/regression_tests/lattice/test.py index 34c598680b..a32b9a629c 100644 --- a/tests/regression_tests/lattice/test.py +++ b/tests/regression_tests/lattice/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_lattice(request): +def test_lattice(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_hex/test.py b/tests/regression_tests/lattice_hex/test.py index b0028f3c52..eb63f84df5 100644 --- a/tests/regression_tests/lattice_hex/test.py +++ b/tests/regression_tests/lattice_hex/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_lattice_hex(request): +def test_lattice_hex(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_mixed/test.py b/tests/regression_tests/lattice_mixed/test.py index 2feb9a1381..3df1d7a4f3 100644 --- a/tests/regression_tests/lattice_mixed/test.py +++ b/tests/regression_tests/lattice_mixed/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_lattice_mixed(request): +def test_lattice_mixed(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/lattice_multiple/test.py b/tests/regression_tests/lattice_multiple/test.py index 15daf0beac..f0672d9a4e 100644 --- a/tests/regression_tests/lattice_multiple/test.py +++ b/tests/regression_tests/lattice_multiple/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_lattice_multiple(request): +def test_lattice_multiple(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_basic/test.py b/tests/regression_tests/mg_basic/test.py index 7b4ec247a6..3c22e60408 100644 --- a/tests/regression_tests/mg_basic/test.py +++ b/tests/regression_tests/mg_basic/test.py @@ -3,8 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_basic(request, reset_ids): +def test_mg_basic(): model = slab_mg() harness = PyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_convert/test.py b/tests/regression_tests/mg_convert/test.py index f51e4e87b9..e6a8690c22 100755 --- a/tests/regression_tests/mg_convert/test.py +++ b/tests/regression_tests/mg_convert/test.py @@ -198,7 +198,6 @@ class MGXSTestHarness(PyAPITestHarness): self._cleanup() -def test_mg_convert(request): +def test_mg_convert(): harness = MGXSTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_legendre/test.py b/tests/regression_tests/mg_legendre/test.py index 58ea4a1dc4..5a57f758e8 100644 --- a/tests/regression_tests/mg_legendre/test.py +++ b/tests/regression_tests/mg_legendre/test.py @@ -3,10 +3,9 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_legendre(request, reset_ids): +def test_mg_legendre(): model = slab_mg(reps=['iso']) model.settings.tabular_legendre = {'enable': False} harness = PyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_max_order/test.py b/tests/regression_tests/mg_max_order/test.py index 72bca32317..20cc4f805d 100644 --- a/tests/regression_tests/mg_max_order/test.py +++ b/tests/regression_tests/mg_max_order/test.py @@ -3,9 +3,8 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_max_order(request, reset_ids): +def test_mg_max_order(): model = slab_mg(reps=['iso']) model.settings.max_order = 1 harness = PyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_nuclide/test.py b/tests/regression_tests/mg_nuclide/test.py index 53eac5e8d5..44206ef28f 100644 --- a/tests/regression_tests/mg_nuclide/test.py +++ b/tests/regression_tests/mg_nuclide/test.py @@ -3,8 +3,7 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_nuclide(request, reset_ids): +def test_mg_nuclide(): model = slab_mg(as_macro=False) harness = PyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_survival_biasing/test.py b/tests/regression_tests/mg_survival_biasing/test.py index 09a210d046..3c6c77a370 100644 --- a/tests/regression_tests/mg_survival_biasing/test.py +++ b/tests/regression_tests/mg_survival_biasing/test.py @@ -3,9 +3,8 @@ from openmc.examples import slab_mg from tests.testing_harness import PyAPITestHarness -def test_mg_survival_biasing(request, reset_ids): +def test_mg_survival_biasing(): model = slab_mg() model.settings.survival_biasing = True harness = PyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mg_tallies/test.py b/tests/regression_tests/mg_tallies/test.py index 3f9bcae79f..8952cc4ad8 100644 --- a/tests/regression_tests/mg_tallies/test.py +++ b/tests/regression_tests/mg_tallies/test.py @@ -4,7 +4,7 @@ from openmc.examples import slab_mg from tests.testing_harness import HashedPyAPITestHarness -def test_mg_tallies(request, reset_ids): +def test_mg_tallies(): model = slab_mg(as_macro=False) # Instantiate a tally mesh @@ -88,5 +88,4 @@ def test_mg_tallies(request, reset_ids): model.tallies.append(t) harness = HashedPyAPITestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/test.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py index 9246694ea9..9dc640acd1 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/test.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -76,10 +76,9 @@ class MGXSTestHarness(PyAPITestHarness): os.remove(f) -def test_mgxs_library_ce_to_mg(request, reset_ids): +def test_mgxs_library_ce_to_mg(): # Set the input set to use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_condense/test.py b/tests/regression_tests/mgxs_library_condense/test.py index b7ecf8925c..06b4704784 100644 --- a/tests/regression_tests/mgxs_library_condense/test.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -60,9 +60,8 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_condense(request, reset_ids): +def test_mgxs_library_condense(): # Use the pincell model model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_distribcell/test.py b/tests/regression_tests/mgxs_library_distribcell/test.py index b9f343eafa..d7bc84bf57 100644 --- a/tests/regression_tests/mgxs_library_distribcell/test.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -64,8 +64,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_distribcell(request, reset_ids): +def test_mgxs_library_distribcell(): model = pwr_assembly() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_hdf5/test.py b/tests/regression_tests/mgxs_library_hdf5/test.py index 38dbeef1a5..8eed0258aa 100644 --- a/tests/regression_tests/mgxs_library_hdf5/test.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -73,12 +73,11 @@ class MGXSTestHarness(PyAPITestHarness): os.remove(f) -def test_mgxs_library_hdf5(request, reset_ids): +def test_mgxs_library_hdf5(): try: np.set_printoptions(formatter={'float_kind': '{:.8e}'.format}) model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() finally: np.set_printoptions(formatter=None) diff --git a/tests/regression_tests/mgxs_library_mesh/test.py b/tests/regression_tests/mgxs_library_mesh/test.py index 809782467d..70bd2113ce 100644 --- a/tests/regression_tests/mgxs_library_mesh/test.py +++ b/tests/regression_tests/mgxs_library_mesh/test.py @@ -65,7 +65,6 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_mesh(request): +def test_mgxs_library_mesh(): harness = MGXSTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_no_nuclides/test.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py index 3e6e236480..c59b52189e 100644 --- a/tests/regression_tests/mgxs_library_no_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -57,8 +57,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_no_nuclides(request, reset_ids): +def test_mgxs_library_no_nuclides(): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/mgxs_library_nuclides/test.py b/tests/regression_tests/mgxs_library_nuclides/test.py index c670e18e30..a65fb9a6d3 100644 --- a/tests/regression_tests/mgxs_library_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -53,8 +53,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr -def test_mgxs_library_nuclides(request, reset_ids): +def test_mgxs_library_nuclides(): model = pwr_pin_cell() harness = MGXSTestHarness('statepoint.10.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/multipole/test.py b/tests/regression_tests/multipole/test.py index d7ed3ca7c0..43aa9963aa 100644 --- a/tests/regression_tests/multipole/test.py +++ b/tests/regression_tests/multipole/test.py @@ -80,8 +80,7 @@ class MultipoleTestHarness(PyAPITestHarness): return outstr -def test_multipole(request, reset_ids): +def test_multipole(): model = make_model() harness = MultipoleTestHarness('statepoint.5.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/output/test.py b/tests/regression_tests/output/test.py index 30fcc3a80c..d9568ba4b0 100644 --- a/tests/regression_tests/output/test.py +++ b/tests/regression_tests/output/test.py @@ -23,7 +23,6 @@ class OutputTestHarness(TestHarness): os.remove(f) -def test_output(request): +def test_output(): harness = OutputTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/particle_restart_eigval/test.py b/tests/regression_tests/particle_restart_eigval/test.py index 6b9d103fdb..a30eb97870 100644 --- a/tests/regression_tests/particle_restart_eigval/test.py +++ b/tests/regression_tests/particle_restart_eigval/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import ParticleRestartTestHarness -def test_particle_restart_eigval(request): +def test_particle_restart_eigval(): harness = ParticleRestartTestHarness('particle_10_1030.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/particle_restart_fixed/test.py b/tests/regression_tests/particle_restart_fixed/test.py index 428d9586d9..463568ecca 100644 --- a/tests/regression_tests/particle_restart_fixed/test.py +++ b/tests/regression_tests/particle_restart_fixed/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import ParticleRestartTestHarness -def test_particle_restart_fixed(request): +def test_particle_restart_fixed(): harness = ParticleRestartTestHarness('particle_7_144.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/periodic/test.py b/tests/regression_tests/periodic/test.py index 188827a5dc..d746ebdd5f 100644 --- a/tests/regression_tests/periodic/test.py +++ b/tests/regression_tests/periodic/test.py @@ -51,7 +51,6 @@ class PeriodicTest(PyAPITestHarness): settings.export_to_xml() -def test_periodic(request): +def test_periodic(): harness = PeriodicTest('statepoint.4.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/plot/test.py b/tests/regression_tests/plot/test.py index 1e7773ea6a..64f2d4d31a 100644 --- a/tests/regression_tests/plot/test.py +++ b/tests/regression_tests/plot/test.py @@ -56,8 +56,7 @@ class PlotTestHarness(TestHarness): return outstr -def test_plot(request): +def test_plot(): harness = PlotTestHarness(('plot_1.ppm', 'plot_2.ppm', 'plot_3.ppm', 'plot_4.h5')) - harness.request = request harness.main() diff --git a/tests/regression_tests/ptables_off/test.py b/tests/regression_tests/ptables_off/test.py index 8d67cf400b..cc316f8c3e 100644 --- a/tests/regression_tests/ptables_off/test.py +++ b/tests/regression_tests/ptables_off/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_ptables_off(request): +def test_ptables_off(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/quadric_surfaces/test.py b/tests/regression_tests/quadric_surfaces/test.py index f919f1648c..862ee9bf41 100755 --- a/tests/regression_tests/quadric_surfaces/test.py +++ b/tests/regression_tests/quadric_surfaces/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_quadric_surfaces(request): +def test_quadric_surfaces(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/reflective_plane/test.py b/tests/regression_tests/reflective_plane/test.py index ba693c61aa..906174f338 100644 --- a/tests/regression_tests/reflective_plane/test.py +++ b/tests/regression_tests/reflective_plane/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_reflective_plane(request): +def test_reflective_plane(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/resonance_scattering/test.py b/tests/regression_tests/resonance_scattering/test.py index 98096a0cac..15e9d68944 100644 --- a/tests/regression_tests/resonance_scattering/test.py +++ b/tests/regression_tests/resonance_scattering/test.py @@ -42,7 +42,6 @@ class ResonanceScatteringTestHarness(PyAPITestHarness): settings.export_to_xml() -def test_resonance_scattering(request): +def test_resonance_scattering(): harness = ResonanceScatteringTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/rotation/test.py b/tests/regression_tests/rotation/test.py index b27e7faa4b..31c3d8d655 100644 --- a/tests/regression_tests/rotation/test.py +++ b/tests/regression_tests/rotation/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_rotation(request): +def test_rotation(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/salphabeta/test.py b/tests/regression_tests/salphabeta/test.py index 62ccbb2267..e69ada5ba3 100644 --- a/tests/regression_tests/salphabeta/test.py +++ b/tests/regression_tests/salphabeta/test.py @@ -73,8 +73,7 @@ def make_model(): return model -def test_salphabeta(request, reset_ids): +def test_salphabeta(): model = make_model() harness = PyAPITestHarness('statepoint.5.h5', model) - harness.request = request harness.main() diff --git a/tests/regression_tests/score_current/test.py b/tests/regression_tests/score_current/test.py index 1acc7c604f..21c5d08812 100644 --- a/tests/regression_tests/score_current/test.py +++ b/tests/regression_tests/score_current/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import HashedTestHarness -def test_score_current(request): +def test_score_current(): harness = HashedTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/seed/test.py b/tests/regression_tests/seed/test.py index 4c6bf95dc2..8b2f031b3e 100644 --- a/tests/regression_tests/seed/test.py +++ b/tests/regression_tests/seed/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_seed(request): +def test_seed(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/source/test.py b/tests/regression_tests/source/test.py index aa17143f0d..00171a2551 100644 --- a/tests/regression_tests/source/test.py +++ b/tests/regression_tests/source/test.py @@ -58,7 +58,6 @@ class SourceTestHarness(PyAPITestHarness): settings.export_to_xml() -def test_source(request): +def test_source(): harness = SourceTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/source_file/test.py b/tests/regression_tests/source_file/test.py index 1989de4c90..b4d9c4a31d 100644 --- a/tests/regression_tests/source_file/test.py +++ b/tests/regression_tests/source_file/test.py @@ -96,7 +96,6 @@ class SourceFileTestHarness(TestHarness): fh.write(settings1) -def test_source_file(request): +def test_source_file(): harness = SourceFileTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_batch/test.py b/tests/regression_tests/sourcepoint_batch/test.py index 96326d15b8..3086b5610d 100644 --- a/tests/regression_tests/sourcepoint_batch/test.py +++ b/tests/regression_tests/sourcepoint_batch/test.py @@ -26,7 +26,6 @@ class SourcepointTestHarness(TestHarness): return outstr -def test_sourcepoint_batch(request): +def test_sourcepoint_batch(): harness = SourcepointTestHarness('statepoint.08.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_latest/test.py b/tests/regression_tests/sourcepoint_latest/test.py index 15082e6d82..d14b566ad8 100644 --- a/tests/regression_tests/sourcepoint_latest/test.py +++ b/tests/regression_tests/sourcepoint_latest/test.py @@ -13,7 +13,6 @@ class SourcepointTestHarness(TestHarness): 'exist.' -def test_sourcepoint_latest(request): +def test_sourcepoint_latest(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/sourcepoint_restart/test.py b/tests/regression_tests/sourcepoint_restart/test.py index b0d2e9069a..32f53ec238 100644 --- a/tests/regression_tests/sourcepoint_restart/test.py +++ b/tests/regression_tests/sourcepoint_restart/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_sourcepoint_restart(request): +def test_sourcepoint_restart(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_batch/test.py b/tests/regression_tests/statepoint_batch/test.py index aeb91e2a6e..6c5e4de318 100644 --- a/tests/regression_tests/statepoint_batch/test.py +++ b/tests/regression_tests/statepoint_batch/test.py @@ -13,7 +13,6 @@ class StatepointTestHarness(TestHarness): TestHarness._test_output_created(self) -def test_statepoint_batch(request): +def test_statepoint_batch(): harness = StatepointTestHarness() - harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_restart/test.py b/tests/regression_tests/statepoint_restart/test.py index 219a8a7ed8..2ee2e7be79 100644 --- a/tests/regression_tests/statepoint_restart/test.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -54,8 +54,7 @@ class StatepointRestartTestHarness(TestHarness): openmc.run(openmc_exec=self._opts.exe, restart_file=statepoint) -def test_statepoint_restart(request): +def test_statepoint_restart(): harness = StatepointRestartTestHarness('statepoint.10.h5', 'statepoint.07.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/statepoint_sourcesep/test.py b/tests/regression_tests/statepoint_sourcesep/test.py index 44a45d406f..3d63ca8ee5 100644 --- a/tests/regression_tests/statepoint_sourcesep/test.py +++ b/tests/regression_tests/statepoint_sourcesep/test.py @@ -20,7 +20,6 @@ class SourcepointTestHarness(TestHarness): os.remove(f) -def test_statepoint_sourcesep(request): +def test_statepoint_sourcesep(): harness = SourcepointTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/surface_tally/test.py b/tests/regression_tests/surface_tally/test.py index 2d499cb293..6995b7780c 100644 --- a/tests/regression_tests/surface_tally/test.py +++ b/tests/regression_tests/surface_tally/test.py @@ -174,7 +174,6 @@ class SurfaceTallyTestHarness(PyAPITestHarness): return outstr -def test_surface_tally(request): +def test_surface_tally(): harness = SurfaceTallyTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/survival_biasing/test.py b/tests/regression_tests/survival_biasing/test.py index 2dc7c86ab1..39e6faed8e 100644 --- a/tests/regression_tests/survival_biasing/test.py +++ b/tests/regression_tests/survival_biasing/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_survival_biasing(request): +def test_survival_biasing(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/tallies/test.py b/tests/regression_tests/tallies/test.py index 3f6f7de748..e3aebfd986 100644 --- a/tests/regression_tests/tallies/test.py +++ b/tests/regression_tests/tallies/test.py @@ -4,9 +4,8 @@ from openmc import Mesh, Tally, Tallies from tests.testing_harness import HashedPyAPITestHarness -def test_tallies(request, reset_ids): +def test_tallies(): harness = HashedPyAPITestHarness('statepoint.5.h5') - harness.request = request model = harness._model # Set settings explicitly diff --git a/tests/regression_tests/tally_aggregation/test.py b/tests/regression_tests/tally_aggregation/test.py index dfa0266902..f723160737 100644 --- a/tests/regression_tests/tally_aggregation/test.py +++ b/tests/regression_tests/tally_aggregation/test.py @@ -61,7 +61,6 @@ class TallyAggregationTestHarness(PyAPITestHarness): return outstr -def test_tally_aggregation(request): +def test_tally_aggregation(): harness = TallyAggregationTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/tally_arithmetic/test.py b/tests/regression_tests/tally_arithmetic/test.py index c87d0149f4..469ed00de1 100644 --- a/tests/regression_tests/tally_arithmetic/test.py +++ b/tests/regression_tests/tally_arithmetic/test.py @@ -75,7 +75,6 @@ class TallyArithmeticTestHarness(PyAPITestHarness): return outstr -def test_tally_arithmetic(request): +def test_tally_arithmetic(): harness = TallyArithmeticTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/tally_assumesep/test.py b/tests/regression_tests/tally_assumesep/test.py index c4248c10af..64595ced22 100644 --- a/tests/regression_tests/tally_assumesep/test.py +++ b/tests/regression_tests/tally_assumesep/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_tally_assumesep(request): +def test_tally_assumesep(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/tally_nuclides/test.py b/tests/regression_tests/tally_nuclides/test.py index 7eec5ef3f1..ee1f4b600e 100644 --- a/tests/regression_tests/tally_nuclides/test.py +++ b/tests/regression_tests/tally_nuclides/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_tally_nuclides(request): +def test_tally_nuclides(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/tally_slice_merge/test.py b/tests/regression_tests/tally_slice_merge/test.py index 4ee99d34a8..c198411f7d 100644 --- a/tests/regression_tests/tally_slice_merge/test.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -166,7 +166,6 @@ class TallySliceMergeTestHarness(PyAPITestHarness): return outstr -def test_tally_slice_merge(request): +def test_tally_slice_merge(): harness = TallySliceMergeTestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/trace/test.py b/tests/regression_tests/trace/test.py index c037bb23bf..79dcaa1060 100644 --- a/tests/regression_tests/trace/test.py +++ b/tests/regression_tests/trace/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_trace(request): +def test_trace(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/track_output/test.py b/tests/regression_tests/track_output/test.py index f3d665e11e..22eac03bfc 100644 --- a/tests/regression_tests/track_output/test.py +++ b/tests/regression_tests/track_output/test.py @@ -38,10 +38,9 @@ class TrackTestHarness(TestHarness): os.remove(f) -def test_track_output(request): +def test_track_output(): # If vtk python module is not available, we can't run track.py so skip this # test. vtk = pytest.importorskip('vtk') harness = TrackTestHarness('statepoint.2.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/translation/test.py b/tests/regression_tests/translation/test.py index 29ef1c0114..876db736b9 100644 --- a/tests/regression_tests/translation/test.py +++ b/tests/regression_tests/translation/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_translation(request): +def test_translation(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_batch_interval/test.py b/tests/regression_tests/trigger_batch_interval/test.py index 1ac01a08bf..e161745022 100644 --- a/tests/regression_tests/trigger_batch_interval/test.py +++ b/tests/regression_tests/trigger_batch_interval/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_trigger_batch_interval(request): +def test_trigger_batch_interval(): harness = TestHarness('statepoint.15.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_no_batch_interval/test.py b/tests/regression_tests/trigger_no_batch_interval/test.py index d38304feea..4a40def5aa 100644 --- a/tests/regression_tests/trigger_no_batch_interval/test.py +++ b/tests/regression_tests/trigger_no_batch_interval/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_trigger_no_batch_interval(request): +def test_trigger_no_batch_interval(): harness = TestHarness('statepoint.15.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_no_status/test.py b/tests/regression_tests/trigger_no_status/test.py index 98173f8dda..75ae9a8cc9 100644 --- a/tests/regression_tests/trigger_no_status/test.py +++ b/tests/regression_tests/trigger_no_status/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_trigger_no_status(request): +def test_trigger_no_status(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/trigger_tallies/test.py b/tests/regression_tests/trigger_tallies/test.py index fde7298ffe..f8493c0c68 100644 --- a/tests/regression_tests/trigger_tallies/test.py +++ b/tests/regression_tests/trigger_tallies/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_trigger_tallies(request): +def test_trigger_tallies(): harness = TestHarness('statepoint.15.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/triso/test.py b/tests/regression_tests/triso/test.py index 2da26d1d38..174bba94fd 100644 --- a/tests/regression_tests/triso/test.py +++ b/tests/regression_tests/triso/test.py @@ -90,7 +90,6 @@ class TRISOTestHarness(PyAPITestHarness): mats.export_to_xml() -def test_triso(request): +def test_triso(): harness = TRISOTestHarness('statepoint.5.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/uniform_fs/test.py b/tests/regression_tests/uniform_fs/test.py index 553484e0ab..64d997909c 100644 --- a/tests/regression_tests/uniform_fs/test.py +++ b/tests/regression_tests/uniform_fs/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_uniform_fs(request): +def test_uniform_fs(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/universe/test.py b/tests/regression_tests/universe/test.py index 5da34d90c8..d5ed9645bd 100644 --- a/tests/regression_tests/universe/test.py +++ b/tests/regression_tests/universe/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_universe(request): +def test_universe(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/void/test.py b/tests/regression_tests/void/test.py index a08813c45b..af16f2ac80 100644 --- a/tests/regression_tests/void/test.py +++ b/tests/regression_tests/void/test.py @@ -1,7 +1,6 @@ from tests.testing_harness import TestHarness -def test_void(request): +def test_void(): harness = TestHarness('statepoint.10.h5') - harness.request = request harness.main() diff --git a/tests/regression_tests/volume_calc/test.py b/tests/regression_tests/volume_calc/test.py index da3a66c36f..a6b62b9be9 100644 --- a/tests/regression_tests/volume_calc/test.py +++ b/tests/regression_tests/volume_calc/test.py @@ -73,7 +73,6 @@ class VolumeTest(PyAPITestHarness): def _test_output_created(self): pass -def test_volume_calc(request): +def test_volume_calc(): harness = VolumeTest('') - harness.request = request harness.main() diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 9aee4f741a..9901dcb718 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -32,14 +32,10 @@ class TestHarness(object): def main(self): """Accept commandline arguments and either run or update tests.""" (self._opts, self._args) = self.parser.parse_args() - try: - olddir = self.request.fspath.dirpath().chdir() - if self._opts.update: - self.update_results() - else: - self.execute_test() - finally: - olddir.chdir() + if self._opts.update: + self.update_results() + else: + self.execute_test() def execute_test(self): """Run OpenMC with the appropriate arguments and check the outputs.""" @@ -237,7 +233,6 @@ class PyAPITestHarness(TestHarness): super(PyAPITestHarness, self).__init__(statepoint_name) self.parser.add_option('-b', '--build-inputs', dest='build_only', action='store_true', default=False) - openmc.reset_auto_ids() if model is None: self._model = pwr_core() else: @@ -248,16 +243,12 @@ class PyAPITestHarness(TestHarness): def main(self): """Accept commandline arguments and either run or update tests.""" (self._opts, self._args) = self.parser.parse_args() - try: - olddir = self.request.fspath.dirpath().chdir() - if self._opts.build_only: - self._build_inputs() - elif self._opts.update: - self.update_results() - else: - self.execute_test() - finally: - olddir.chdir() + if self._opts.build_only: + self._build_inputs() + elif self._opts.update: + self.update_results() + else: + self.execute_test() def execute_test(self): """Build input XMLs, run OpenMC, and verify correct results.""" From 0d3845c32744b59dc1c99b3bb28111b6ad793a0f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 13:46:40 -0600 Subject: [PATCH 053/212] Fix command-line arguments for regression tests --- tests/conftest.py | 17 +++++++++ tests/regression_tests/__init__.py | 9 +++++ tests/regression_tests/mg_convert/test.py | 25 ++++++------- .../mgxs_library_ce_to_mg/test.py | 17 ++++----- tests/regression_tests/plot/test.py | 11 +++--- .../statepoint_restart/test.py | 9 ++--- tests/testing_harness.py | 35 +++++++------------ tests/unit_tests/test_capi.py | 1 + tools/ci/travis-script.sh | 14 ++++---- 9 files changed, 75 insertions(+), 63 deletions(-) create mode 100644 tests/conftest.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000..422c036fb3 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,17 @@ +from tests.regression_tests import config as regression_config + + +def pytest_addoption(parser): + parser.addoption('--exe') + parser.addoption('--mpi', action='store_true') + parser.addoption('--mpiexec') + parser.addoption('--mpi-np') + parser.addoption('--update', action='store_true') + parser.addoption('--build-inputs', action='store_true') + + +def pytest_configure(config): + opts = ['exe', 'mpi', 'mpiexec', 'mpi_np', 'update', 'build_inputs'] + for opt in opts: + if config.getoption(opt) is not None: + regression_config[opt] = config.getoption(opt) diff --git a/tests/regression_tests/__init__.py b/tests/regression_tests/__init__.py index e69de29bb2..965a7f94db 100644 --- a/tests/regression_tests/__init__.py +++ b/tests/regression_tests/__init__.py @@ -0,0 +1,9 @@ +# Test configuration options for regression tests +config = { + 'exe': 'openmc', + 'mpi': False, + 'mpiexec': 'mpiexec', + 'mpi_np': '2', + 'update': False, + 'build_inputs': False +} diff --git a/tests/regression_tests/mg_convert/test.py b/tests/regression_tests/mg_convert/test.py index e6a8690c22..4bbbcbeb9a 100755 --- a/tests/regression_tests/mg_convert/test.py +++ b/tests/regression_tests/mg_convert/test.py @@ -5,6 +5,7 @@ import numpy as np import openmc from tests.testing_harness import PyAPITestHarness +from tests.regression_tests import config # OpenMC simulation parameters batches = 10 @@ -133,24 +134,18 @@ class MGXSTestHarness(PyAPITestHarness): for case in cases: build_mgxs_library(case) - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) - sp = openmc.StatePoint('statepoint.' + str(batches) + '.h5') - - # Write out k-combined. - outstr += 'k-combined:\n' - form = '{0:12.6E} {1:12.6E}\n' - outstr += form.format(sp.k_combined[0], sp.k_combined[1]) - - # Enforce closing statepoint and summary files so HDF5 - # does not throw an error during the next OpenMC execution - sp._f.close() - sp._summary._f.close() + with openmc.StatePoint('statepoint.{}.h5'.format(batches)) as sp: + # Write out k-combined. + outstr += 'k-combined:\n' + form = '{0:12.6E} {1:12.6E}\n' + outstr += form.format(sp.k_combined[0], sp.k_combined[1]) return outstr diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/test.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py index 9dc640acd1..922b2c302c 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/test.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -5,6 +5,7 @@ import openmc.mgxs from openmc.examples import pwr_pin_cell from tests.testing_harness import PyAPITestHarness +from tests.regression_tests import config class MGXSTestHarness(PyAPITestHarness): @@ -31,11 +32,11 @@ class MGXSTestHarness(PyAPITestHarness): def _run_openmc(self): # Initial run - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) # Build MG Inputs # Get data needed to execute Library calculations. @@ -63,11 +64,11 @@ class MGXSTestHarness(PyAPITestHarness): sp._summary._f.close() # Re-run MG mode. - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - openmc.run(openmc_exec=self._opts.exe, mpi_args=mpi_args) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) def _cleanup(self): super(MGXSTestHarness, self)._cleanup() diff --git a/tests/regression_tests/plot/test.py b/tests/regression_tests/plot/test.py index 64f2d4d31a..e7115c4dde 100644 --- a/tests/regression_tests/plot/test.py +++ b/tests/regression_tests/plot/test.py @@ -6,6 +6,7 @@ import h5py import openmc from tests.testing_harness import TestHarness +from tests.regression_tests import config class PlotTestHarness(TestHarness): @@ -15,20 +16,18 @@ class PlotTestHarness(TestHarness): self._plot_names = plot_names def _run_openmc(self): - openmc.plot_geometry(openmc_exec=self._opts.exe) + openmc.plot_geometry(openmc_exec=config['exe']) def _test_output_created(self): """Make sure *.ppm has been created.""" for fname in self._plot_names: - assert os.path.exists(os.path.join(os.getcwd(), fname)), \ - 'Plot output file does not exist.' + assert os.path.exists(fname), 'Plot output file does not exist.' def _cleanup(self): super(PlotTestHarness, self)._cleanup() for fname in self._plot_names: - path = os.path.join(os.getcwd(), fname) - if os.path.exists(path): - os.remove(path) + if os.path.exists(fname): + os.remove(fname) def _get_results(self): """Return a string hash of the plot files.""" diff --git a/tests/regression_tests/statepoint_restart/test.py b/tests/regression_tests/statepoint_restart/test.py index 2ee2e7be79..d36ff93950 100644 --- a/tests/regression_tests/statepoint_restart/test.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -4,6 +4,7 @@ import os import openmc from tests.testing_harness import TestHarness +from tests.regression_tests import config class StatepointRestartTestHarness(TestHarness): @@ -46,12 +47,12 @@ class StatepointRestartTestHarness(TestHarness): statepoint = statepoint[0] # Run OpenMC - if self._opts.mpi_exec is not None: - mpi_args = [self._opts.mpi_exec, '-n', self._opts.mpi_np] - openmc.run(restart_file=statepoint, openmc_exec=self._opts.exe, + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(restart_file=statepoint, openmc_exec=config['exe'], mpi_args=mpi_args) else: - openmc.run(openmc_exec=self._opts.exe, restart_file=statepoint) + openmc.run(openmc_exec=config['exe'], restart_file=statepoint) def test_statepoint_restart(): diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 9901dcb718..55a5660f1c 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -10,29 +10,21 @@ import shutil import sys import numpy as np - import openmc from openmc.examples import pwr_core +from tests.regression_tests import config + class TestHarness(object): """General class for running OpenMC regression tests.""" def __init__(self, statepoint_name): self._sp_name = statepoint_name - self.parser = OptionParser() - self.parser.add_option('--exe', dest='exe', default='openmc') - self.parser.add_option('--mpi_exec', dest='mpi_exec', default=None) - self.parser.add_option('--mpi_np', dest='mpi_np', default='2') - self.parser.add_option('--update', dest='update', action='store_true', - default=False) - self._opts = None - self._args = None def main(self): """Accept commandline arguments and either run or update tests.""" - (self._opts, self._args) = self.parser.parse_args() - if self._opts.update: + if config['update']: self.update_results() else: self.execute_test() @@ -60,11 +52,11 @@ class TestHarness(object): self._cleanup() def _run_openmc(self): - if self._opts.mpi_exec is not None: - openmc.run(openmc_exec=self._opts.exe, - mpi_args=[self._opts.mpi_exec, '-n', self._opts.mpi_np]) + if config['mpi']: + mpi_args = [config['mpiexec'], '-n', config['mpi_np']] + openmc.run(openmc_exec=config['exe'], mpi_args=mpi_args) else: - openmc.run(openmc_exec=self._opts.exe) + openmc.run(openmc_exec=config['exe']) def _test_output_created(self): """Make sure statepoint.* and tallies.out have been created.""" @@ -179,9 +171,9 @@ class ParticleRestartTestHarness(TestHarness): def _run_openmc(self): # Set arguments - args = {'openmc_exec': self._opts.exe} - if self._opts.mpi_exec is not None: - args['mpi_args'] = [self._opts.mpi_exec, '-n', self._opts.mpi_np] + args = {'openmc_exec': config['exe']} + if config['mpi']: + args['mpi_args'] = [config['mpiexec'], '-n', config['mpi_np']] # Initial run openmc.run(**args) @@ -231,8 +223,6 @@ class ParticleRestartTestHarness(TestHarness): class PyAPITestHarness(TestHarness): def __init__(self, statepoint_name, model=None): super(PyAPITestHarness, self).__init__(statepoint_name) - self.parser.add_option('-b', '--build-inputs', dest='build_only', - action='store_true', default=False) if model is None: self._model = pwr_core() else: @@ -242,10 +232,9 @@ class PyAPITestHarness(TestHarness): def main(self): """Accept commandline arguments and either run or update tests.""" - (self._opts, self._args) = self.parser.parse_args() - if self._opts.build_only: + if config['build_inputs']: self._build_inputs() - elif self._opts.update: + elif config['update']: self.update_results() else: self.execute_test() diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index ba9ac5c9e0..e1e87e27b3 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -12,6 +12,7 @@ import openmc.capi @pytest.fixture(scope='module') def pincell_model(): """Set up a model to test with and delete files when done""" + openmc.reset_auto_ids() pincell = openmc.examples.pwr_pin_cell() # Add a tally diff --git a/tools/ci/travis-script.sh b/tools/ci/travis-script.sh index 2934cb59a0..468cd0cc8a 100755 --- a/tools/ci/travis-script.sh +++ b/tools/ci/travis-script.sh @@ -1,15 +1,15 @@ #!/bin/bash set -ex -# Run regression test suite -cd build -ctest - # Run source check -cd ../tests +cd tests if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OMP == 'n' && $MPI == 'n' ]]; then ./check_source.py fi -# Run unit tests -pytest --cov=../openmc -v unit_tests/ +# Run regression and unit tests +if [[ $MPI == 'y' ]]; then + pytest --cov=../openmc -v --mpi +else + pytest --cov=../openmc -v +fi From ea15a931042f231500cb2b853825f35d619f162c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 14:05:48 -0600 Subject: [PATCH 054/212] Remove use of ctest / update_results.py --- CMakeLists.txt | 49 ----------------------------- tests/convert_precision.py | 23 -------------- tests/update_results.py | 60 ------------------------------------ tests/valgrind.supp | 63 -------------------------------------- 4 files changed, 195 deletions(-) delete mode 100755 tests/convert_precision.py delete mode 100755 tests/update_results.py delete mode 100644 tests/valgrind.supp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5d0fcb0ab3..78db0ab453 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -522,52 +522,3 @@ if(PYTHONINTERP_FOUND) WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})") endif() endif() - -#=============================================================================== -# Regression tests -#=============================================================================== - -# This allows for dashboard configuration -include(CTest) - -# Get a list of all the tests to run -file(GLOB_RECURSE TESTS ${CMAKE_CURRENT_SOURCE_DIR}/tests/test.py) - -# Loop through all the tests -foreach(test ${TESTS}) - # Remove unit tests - if(test MATCHES ".*unit_tests.*") - continue() - endif() - - # Get test information - get_filename_component(TEST_NAME ${test} NAME) - get_filename_component(TEST_PATH ${test} PATH) - - if (DEFINED ENV{MEM_CHECK}) - # Generate input files if needed - if (NOT EXISTS "${TEST_PATH}/geometry.xml") - execute_process(COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --build-inputs - WORKING_DIRECTORY ${TEST_PATH}) - endif() - - # Add serial test - add_test(NAME ${TEST_PATH} - WORKING_DIRECTORY ${TEST_PATH} - COMMAND $) - else() - # Check serial/parallel - if (${MPI_ENABLED}) - # Preform a parallel test - add_test(NAME ${TEST_PATH} - WORKING_DIRECTORY ${TEST_PATH} - COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $ - --mpi_exec ${MPI_DIR}/mpiexec) - else() - # Perform a serial test - add_test(NAME ${TEST_PATH} - WORKING_DIRECTORY ${TEST_PATH} - COMMAND ${PYTHON_EXECUTABLE} ${TEST_NAME} --exe $) - endif() - endif() -endforeach(test) diff --git a/tests/convert_precision.py b/tests/convert_precision.py deleted file mode 100755 index 625fe49ca9..0000000000 --- a/tests/convert_precision.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -import os -import glob - -dirs = glob.glob('test_*') - -for adir in dirs: - - os.chdir(adir) - - files = glob.glob('results.py') - - if len(files) > 0: - - files = files[0] - with open(files, 'r') as fh: - intxt = fh.read() - intxt = intxt.replace('14.8E', '12.6E') - with open(files, 'w') as fh: - fh.write(intxt) - - os.chdir('..') diff --git a/tests/update_results.py b/tests/update_results.py deleted file mode 100755 index 5656003331..0000000000 --- a/tests/update_results.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python - -from __future__ import print_function - -import os -import re -from subprocess import Popen, call, STDOUT, PIPE -from glob import glob -from optparse import OptionParser - -parser = OptionParser() -parser.add_option('-R', '--tests-regex', dest='regex_tests', - help="Run tests matching regular expression. \ - Test names are the directories present in tests folder.\ - This uses standard regex syntax to select tests.") -(opts, args) = parser.parse_args() -cwd = os.getcwd() - -# Terminal color configurations -OKGREEN = '\033[92m' -FAIL = '\033[91m' -ENDC = '\033[0m' -BOLD = '\033[1m' - -# Get a list of all test folders -folders = glob('test_*') - -# Check to see if a subset of tests is specified on command line -if opts.regex_tests is not None: - folders = [item for item in folders if re.search(opts.regex_tests, item)] - -# Loop around directories -for adir in sorted(folders): - - # Go into that directory - os.chdir(adir) - pwd = os.path.abspath(os.path.dirname('settings.xml')) - os.putenv('PWD', pwd) - - # Print status to screen - print(adir, end="") - sz = len(adir) - for i in range(35 - sz): - print('.', end="") - - # Find the test executable - test_exec = glob('test_*.py') - assert len(test_exec) == 1, 'There must be only one test executable per ' \ - 'test directory' - - # Update the test results - proc = Popen(['python', test_exec[0], '--update']) - returncode = proc.wait() - if returncode == 0: - print(BOLD + OKGREEN + "[OK]" + ENDC) - else: - print(BOLD + FAIL + "[FAILED]" + ENDC) - - # Go back a directory - os.chdir('..') diff --git a/tests/valgrind.supp b/tests/valgrind.supp deleted file mode 100644 index ad302c5397..0000000000 --- a/tests/valgrind.supp +++ /dev/null @@ -1,63 +0,0 @@ -{ - Create HDF5 statepoint file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__state_point_MOD_write_state_point - fun:__eigenvalue_MOD_finalize_batch - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} -{ - Open HDF5 statepoint file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fopen - fun:h5fopen_c_ - fun:__h5f_MOD_h5fopen_f - fun:__hdf5_interface_MOD_hdf5_file_open - fun:__output_interface_MOD_file_open - fun:__state_point_MOD_write_source_point - fun:__eigenvalue_MOD_finalize_batch - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} -{ - Create HDF5 summary file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__hdf5_summary_MOD_hdf5_write_summary - fun:__initialize_MOD_initialize_run - fun:MAIN__ - fun:main -} -{ - Create HDF5 track file - Memcheck:Addr4 - fun:H5_build_extpath - fun:H5F_open - fun:H5Fcreate - fun:h5fcreate_c_ - fun:__h5f_MOD_h5fcreate_f - fun:__hdf5_interface_MOD_hdf5_file_create - fun:__output_interface_MOD_file_create - fun:__track_output_MOD_finalize_particle_track - fun:__tracking_MOD_transport - fun:__eigenvalue_MOD_run_eigenvalue - fun:MAIN__ - fun:main -} From dd2415d35065019d3b1be232dd2babe0b1eb44ce Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 15:26:29 -0600 Subject: [PATCH 055/212] Make sure non-PHDF5 builds turn off prefer_parallel --- tools/ci/travis-install.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tools/ci/travis-install.py b/tools/ci/travis-install.py index 0e4dbdc01b..8fda09b093 100644 --- a/tools/ci/travis-install.py +++ b/tools/ci/travis-install.py @@ -42,13 +42,16 @@ def install(omp=False, mpi=False, phdf5=False): if not mpi: raise ValueError('Parallel HDF5 must be used in ' 'conjunction with MPI.') - cmake_cmd.append('-DHDF5_PREFER_PARALLEL=on') + cmake_cmd.append('-DHDF5_PREFER_PARALLEL=ON') + else: + cmake_cmd.append('-DHDF5_PREFER_PARALLEL=OFF') # Build and install cmake_cmd.append('..') + print(' '.join(cmake_cmd)) subprocess.call(cmake_cmd) subprocess.call(['make', '-j']) - subprocess.call(['make', 'install']) + subprocess.call(['sudo', 'make', 'install']) def main(): From fe353aff401e02a4c3880c49476271ab9cd7150d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 15:45:03 -0600 Subject: [PATCH 056/212] Update documentation relating to test suite --- docs/source/devguide/index.rst | 3 +- docs/source/devguide/tests.rst | 73 ++++++++++++++++ docs/source/devguide/workflow.rst | 133 ----------------------------- docs/source/usersguide/install.rst | 2 +- docs/source/usersguide/scripts.rst | 4 +- tests/readme.rst | 59 +------------ 6 files changed, 79 insertions(+), 195 deletions(-) create mode 100644 docs/source/devguide/tests.rst diff --git a/docs/source/devguide/index.rst b/docs/source/devguide/index.rst index 1a8252383c..e40e7f6359 100644 --- a/docs/source/devguide/index.rst +++ b/docs/source/devguide/index.rst @@ -10,9 +10,10 @@ as debugging. .. toctree:: :numbered: - :maxdepth: 3 + :maxdepth: 2 styleguide workflow + tests user-input docbuild diff --git a/docs/source/devguide/tests.rst b/docs/source/devguide/tests.rst new file mode 100644 index 0000000000..749737b5cb --- /dev/null +++ b/docs/source/devguide/tests.rst @@ -0,0 +1,73 @@ +.. _devguide_tests: + +========== +Test Suite +========== + +Running Tests +------------- + +The OpenMC test suite consists of two parts, a regression test suite and a unit +test suite. The regression test suite is based on regression or integrated +testing where different types of input files are configured and the full OpenMC +code is executed. Results from simulations are compared with expected +results. The unit tests are primarily intended to test individual +functions/classes in the OpenMC Python API. + +The test suite relies on the third-party `pytest `_ +package. To run either or both the regression and unit test suites, it is +assumed that you have OpenMC fully installed, i.e., the :ref:`scripts_openmc` +executable is available on your :envvar:`PATH` and the :mod:`openmc` Python +module is importable. In development where it would be onerous to continually +install OpenMC every time a small change is made, it is recommended to install +OpenMC in development/editable mode. With setuptools, this is accomplished by +running:: + + python setup.py develop + +or using pip (recommended):: + + pip install -e .[test] + +It is also assumed that you have cross section data available that is pointed to +by the :envvar:`OPENMC_CROSS_SECTIONS` and :envvar:`OPENMC_MULTIPOLE_LIBRARY` +environment variables. Furthermore, to run unit tests for the :mod:`openmc.data` +module, it is necessary to have ENDF/B-VII.1 data available and pointed to by +the :envvar:`OPENMC_ENDF_DATA` environment variable. All data sources can be +obtained using the ``tools/ci/travis-before-script.sh`` script. + +To execute the test suite, go to the ``tests/`` directory and run:: + + pytest + +If you want to collect information about source line coverage in the Python API, +you must have the `pytest-cov `_ plugin +installed and run:: + + pytest --cov=../openmc --cov-report=html + +Adding Tests to the Regression Suite +------------------------------------ + +To add a new test to the regression test suite, create a sub-directory in the +``tests/regression_tests/`` directory. To configure a test you need to add the +following files to your new test directory: + + * OpenMC input XML files, if they are not generated through the Python API + * **test.py** - Python test driver script; please refer to other tests to + see how to construct. Any output files that are generated during testing + must be removed at the end of this script. + * **inputs_true.dat** - ASCII file that contains Python API-generated XML + files concatenated together. When the test is run, inputs that are + generated are compared to this file. + * **results_true.dat** - ASCII file that contains the expected results from + the test. The file *results_test.dat* is compared to this file during the + execution of the python test driver script. When the above files have been + created, generate a *results_test.dat* file and copy it to this name and + commit. It should be noted that this file should be generated with basic + compiler options during openmc configuration and build (e.g., no MPI, no + debug/optimization). + +In addition to this description, please see the various types of tests that are +already included in the test suite to see how to create them. If all is +implemented correctly, the new test will automatically be discovered by pytest. diff --git a/docs/source/devguide/workflow.rst b/docs/source/devguide/workflow.rst index 942cee55be..fd1ae0455e 100644 --- a/docs/source/devguide/workflow.rst +++ b/docs/source/devguide/workflow.rst @@ -89,139 +89,6 @@ features and bug fixes. The general steps for contributing are as follows: 6. After the pull request has been thoroughly vetted, it is merged back into the *develop* branch of mit-crpg/openmc. -.. _test suite: - -OpenMC Test Suite ------------------ - -The purpose of this test suite is to ensure that OpenMC compiles using various -combinations of compiler flags and options, and that all user input options can -be used successfully without breaking the code. The test suite is comprised of -regression tests where different types of input files are configured and the -full OpenMC code is executed. Results from simulations are compared with -expected results. The test suite is comprised of many build configurations -(e.g. debug, mpi, hdf5) and the actual tests which reside in sub-directories -in the tests directory. We recommend to developers to test their branches -before submitting a formal pull request using gfortran and Intel compilers -if available. - -The test suite is designed to integrate with cmake using ctest_. It is -configured to run with cross sections from NNDC_ augmented with 0 K elastic -scattering data for select nuclides as well as multipole data. To download the -proper data, run the following commands: - -.. code-block:: sh - - wget -O nndc_hdf5.tar.xz $(cat /.travis.yml | grep anl.box | awk '{print $2}') - tar xJvf nndc_hdf5.tar.xz - export OPENMC_CROSS_SECTIONS=$(pwd)/nndc_hdf5/cross_sections.xml - - git clone --branch=master git://github.com/smharper/windowed_multipole_library.git wmp_lib - tar xzvf wmp_lib/multipole_lib.tar.gz - export OPENMC_MULTIPOLE_LIBRARY=$(pwd)/multipole_lib - -The test suite can be run on an already existing build using: - -.. code-block:: sh - - cd build - make test - -or - -.. code-block:: sh - - cd build - ctest - -There are numerous ctest_ command line options that can be set to have -more control over which tests are executed. - -Before running the test suite python script, the following environmental -variables should be set if the default paths are incorrect: - - * **FC** - The command for a Fortran compiler (e.g. gfotran, ifort). - - * Default - *gfortran* - - * **CC** - The command for a C compiler (e.g. gcc, icc). - - * Default - *gcc* - - * **CXX** - The command for a C++ compiler (e.g. g++, icpc). - - * Default - *g++* - - * **MPI_DIR** - The path to the MPI directory. - - * Default - */opt/mpich/3.2-gnu* - - * **HDF5_DIR** - The path to the HDF5 directory. - - * Default - */opt/hdf5/1.8.16-gnu* - - * **PHDF5_DIR** - The path to the parallel HDF5 directory. - - * Default - */opt/phdf5/1.8.16-gnu* - -To run the full test suite, the following command can be executed in the -tests directory: - -.. code-block:: sh - - python run_tests.py - -A subset of build configurations and/or tests can be run. To see how to use -the script run: - -.. code-block:: sh - - python run_tests.py --help - -As an example, say we want to run all tests with debug flags only on tests -that have cone and plot in their name. Also, we would like to run this on -4 processors. We can run: - -.. code-block:: sh - - python run_tests.py -j 4 -C debug -R "cone|plot" - -Note that standard regular expression syntax is used for selecting build -configurations and tests. To print out a list of build configurations, we -can run: - -.. code-block:: sh - - python run_tests.py -p - -Adding tests to test suite -++++++++++++++++++++++++++ - -To add a new test to the test suite, create a sub-directory in the tests -directory that conforms to the regular expression *test_*. To configure -a test you need to add the following files to your new test directory, -*test_name* for example: - - * OpenMC input XML files - * **test_name.py** - Python test driver script, please refer to other - tests to see how to construct. Any output files that are generated - during testing must be removed at the end of this script. - * **inputs_true.dat** - ASCII file that contains Python API-generated XML - files concatenated together. When the test is run, inputs that are - generated are compared to this file. - * **results_true.dat** - ASCII file that contains the expected results - from the test. The file *results_test.dat* is compared to this file - during the execution of the python test driver script. When the - above files have been created, generate a *results_test.dat* file and - copy it to this name and commit. It should be noted that this file - should be generated with basic compiler options during openmc - configuration and build (e.g., no MPI/HDF5, no debug/optimization). - -In addition to this description, please see the various types of tests that -are already included in the test suite to see how to create them. If all is -implemented correctly, the new test directory will automatically be added -to the CTest framework. - Private Development ------------------- diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index b595729236..6bb685f480 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -364,7 +364,7 @@ Testing Build To run the test suite, you will first need to download a pre-generated cross section library along with windowed multipole data. Please refer to our -:ref:`test suite` documentation for further details. +:ref:`devguide_tests` documentation for further details. -------------------- Python Prerequisites diff --git a/docs/source/usersguide/scripts.rst b/docs/source/usersguide/scripts.rst index 90ca6886d1..2f199fc256 100644 --- a/docs/source/usersguide/scripts.rst +++ b/docs/source/usersguide/scripts.rst @@ -168,8 +168,8 @@ ENDF/B-VII.1. It has the following optional arguments: This script downloads `ENDF/B-VII.1 ACE data `_ from NNDC and converts it to -an HDF5 library for use with OpenMC. This data is used for OpenMC's regression -test suite. This script has the following optional arguments: +an HDF5 library for use with OpenMC. This script has the following optional +arguments: -b, --batch Suppress standard in diff --git a/tests/readme.rst b/tests/readme.rst index f2e2bb1c12..5e4b0227be 100644 --- a/tests/readme.rst +++ b/tests/readme.rst @@ -1,58 +1 @@ -================= -OpenMC Test Suite -================= - -The purpose of this test suite is to ensure that OpenMC compiles using various -combinations of compiler flags and options and that all user input options can -be used successfully without breaking the code. The test suite is based on -regression or integrated testing where different types of input files are -configured and the full OpenMC code is executed. Results from simulations -are compared with expected results. The test suite is comprised of many -build configurations (e.g. debug, mpi, hdf5) and the actual tests which -reside in sub-directories in the tests directory. - -The test suite is designed to integrate with cmake using ctest_. To run the -full test suite run: - -.. code-block:: sh - - python run_tests.py - -The test suite is configured to run with cross sections from NNDC_. To -download these cross sections please do the following: - -.. code-block:: sh - - cd ../data - python get_nndc.py - export CROSS_SECTIONS=/nndc/cross_sections.xml - -The environmental variable **CROSS_SECTIONS** can be used to quickly switch -between the cross sections set for the test suite and cross section set for -your simulations. - -A subset of build configurations and/or tests can be run. To see how to use -the script run: - -.. code-block:: sh - - python run_tests.py --help - -As an example, say we want to run all tests with debug flags only on tests -that have cone and plot in their name. Also, we would like to run this on -4 processors. We can run: - -.. code-block:: sh - - python run_tests.py -j 4 -C debug -R "cone|plot" - -Note that standard regular expression syntax is used for selecting build -configurations and tests. To print out a list of build configurations, we -can run: - -.. code-block:: sh - - python run_tests.py -p - -.. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html -.. _NNDC: http://http://www.nndc.bnl.gov/endf/b7.1/acefiles.html +See docs/source/devguide/tests.rst for information on the OpenMC test suite. From 60909945459dfc76faace3306d767dd9be56b857 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 15:49:30 -0600 Subject: [PATCH 057/212] Make sure IPython<6 is used for Python 2.7 --- tools/ci/travis-install.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 6051f03aa9..3ee54af76c 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -10,6 +10,11 @@ pip install numpy cython # pytest installed by default -- make sure we get latest pip install --upgrade pytest +# IPython stopped supporting Python 2.7 with version 6 +if [[ "$TRAVIS_PYTHON_VERSION" == "2.7" ]]; then + pip install "ipython<6" +fi + # Pandas stopped supporting Python 3.4 with version 0.21 if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then pip install pandas==0.20.3 From 18695c2878a0750814af0e4a7d9ace0da9bdebd8 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 16:30:57 -0600 Subject: [PATCH 058/212] Don't install Python package from CMakeLists.txt --- CMakeLists.txt | 16 ---------------- tools/ci/travis-install.py | 6 +++--- tools/ci/travis-install.sh | 6 +++--- 3 files changed, 6 insertions(+), 22 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 78db0ab453..7ab012ef6d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -506,19 +506,3 @@ install(TARGETS ${program} libopenmc install(DIRECTORY src/relaxng DESTINATION share/openmc) install(FILES man/man1/openmc.1 DESTINATION share/man/man1) install(FILES LICENSE DESTINATION "share/doc/${program}" RENAME copyright) - -find_package(PythonInterp) -if(PYTHONINTERP_FOUND) - if(debian) - install(CODE "execute_process( - COMMAND ${PYTHON_EXECUTABLE} setup.py install - --root=debian/openmc --install-layout=deb - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})") - else() - install(CODE "set(ENV{PYTHONPATH} \"${CMAKE_INSTALL_PREFIX}/lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages\")") - install(CODE "execute_process( - COMMAND ${PYTHON_EXECUTABLE} setup.py install - --prefix=${CMAKE_INSTALL_PREFIX} - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})") - endif() -endif() diff --git a/tools/ci/travis-install.py b/tools/ci/travis-install.py index 8fda09b093..bd7f886dbc 100644 --- a/tools/ci/travis-install.py +++ b/tools/ci/travis-install.py @@ -49,9 +49,9 @@ def install(omp=False, mpi=False, phdf5=False): # Build and install cmake_cmd.append('..') print(' '.join(cmake_cmd)) - subprocess.call(cmake_cmd) - subprocess.call(['make', '-j']) - subprocess.call(['sudo', 'make', 'install']) + subprocess.check_call(cmake_cmd) + subprocess.check_call(['make', '-j']) + subprocess.check_call(['sudo', 'make', 'install']) def main(): diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 3ee54af76c..3723315a4e 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -20,8 +20,8 @@ if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then pip install pandas==0.20.3 fi -# Build and install +# Build and install OpenMC executable python tools/ci/travis-install.py -# Install OpenMC in editable mode -pip install -e .[test] +# Install Python API +pip install .[test] From d75b715026ef881d5d8b62dc5f5abb41a8d10694 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 17:41:10 -0600 Subject: [PATCH 059/212] Add source tests and fix one failing test --- tests/unit_tests/test_source.py | 30 ++++++++++++++++++++++++++++++ tests/unit_tests/test_stats.py | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 tests/unit_tests/test_source.py diff --git a/tests/unit_tests/test_source.py b/tests/unit_tests/test_source.py new file mode 100644 index 0000000000..3c963d0527 --- /dev/null +++ b/tests/unit_tests/test_source.py @@ -0,0 +1,30 @@ +import openmc +import openmc.stats + + +def test_source(): + space = openmc.stats.Point() + energy = openmc.stats.Discrete([1.0e6], [1.0]) + angle = openmc.stats.Isotropic() + + src = openmc.Source(space=space, angle=angle, energy=energy) + assert src.space == space + assert src.angle == angle + assert src.energy == energy + assert src.strength == 1.0 + + elem = src.to_xml_element() + assert 'strength' in elem.attrib + assert elem.find('space') is not None + assert elem.find('angle') is not None + assert elem.find('energy') is not None + + +def test_source_file(): + filename = 'source.h5' + src = openmc.Source(filename=filename) + assert src.file == filename + + elem = src.to_xml_element() + assert 'strength' in elem.attrib + assert 'file' in elem.attrib diff --git a/tests/unit_tests/test_stats.py b/tests/unit_tests/test_stats.py index 3a91ecd8fd..388408bb22 100644 --- a/tests/unit_tests/test_stats.py +++ b/tests/unit_tests/test_stats.py @@ -23,7 +23,7 @@ def test_discrete(): def test_uniform(): - a, b = 10, 20 + a, b = 10.0, 20.0 d = openmc.stats.Uniform(a, b) assert d.a == a assert d.b == b From 54cd34f33e7b9c3e1876ab06e4011482439c4313 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 18:02:03 -0600 Subject: [PATCH 060/212] Install Python package in editable mode once again --- tools/ci/travis-install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 3723315a4e..cef34a2e0e 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -23,5 +23,5 @@ fi # Build and install OpenMC executable python tools/ci/travis-install.py -# Install Python API -pip install .[test] +# Install Python API in editable mode +pip install -e .[test] From 4ad4feecc688f311d1e4ae3555dff3f48c011690 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 22:31:44 -0600 Subject: [PATCH 061/212] Update minimum CMake version to 3.0 --- CMakeLists.txt | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7ab012ef6d..fc8b252954 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 2.8.12 FATAL_ERROR) +cmake_minimum_required(VERSION 3.0 FATAL_ERROR) project(openmc Fortran C CXX) # Setup output directories @@ -21,11 +21,6 @@ if (${UNIX}) add_definitions(-DUNIX) endif() -# Set MACOSX_RPATH -if(POLICY CMP0042) - cmake_policy(SET CMP0042 NEW) -endif() - #=============================================================================== # Command line options #=============================================================================== From f6fc24c808215694b7880a1c4f69c6e59861b5ca Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 29 Jan 2018 23:23:48 -0600 Subject: [PATCH 062/212] Add unit tests for plots --- tests/unit_tests/conftest.py | 10 ++++ tests/unit_tests/test_material.py | 9 ---- tests/unit_tests/test_plots.py | 90 +++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 9 deletions(-) create mode 100644 tests/unit_tests/conftest.py create mode 100644 tests/unit_tests/test_plots.py diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py new file mode 100644 index 0000000000..aad0ac0581 --- /dev/null +++ b/tests/unit_tests/conftest.py @@ -0,0 +1,10 @@ +import pytest + + +@pytest.fixture +def run_in_tmpdir(tmpdir): + orig = tmpdir.chdir() + try: + yield + finally: + orig.chdir() diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 84627ba8c4..b96cbfb4c0 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -40,15 +40,6 @@ def sphere_model(): return model -@pytest.fixture -def run_in_tmpdir(tmpdir): - orig = tmpdir.chdir() - try: - yield - finally: - orig.chdir() - - def test_attributes(uo2): assert uo2.name == 'UO2' assert uo2.id == 100 diff --git a/tests/unit_tests/test_plots.py b/tests/unit_tests/test_plots.py new file mode 100644 index 0000000000..d48b609c1e --- /dev/null +++ b/tests/unit_tests/test_plots.py @@ -0,0 +1,90 @@ +import openmc +import openmc.examples +import pytest + + +@pytest.fixture(scope='module') +def myplot(): + plot = openmc.Plot(name='myplot') + plot.width = (100., 100.) + plot.origin = (2., 3., -10.) + plot.pixels = (500, 500) + plot.filename = 'myplot' + plot.type = 'slice' + plot.basis = 'yz' + plot.background = (0, 0, 0) + plot.background = 'black' + + plot.color_by = 'material' + m1, m2 = openmc.Material(), openmc.Material() + plot.colors = {m1: (0, 255, 0), m2: (0, 0, 255)} + plot.colors = {m1: 'green', m2: 'blue'} + + plot.mask_components = [openmc.Material()] + plot.mask_background = (255, 255, 255) + plot.mask_background = 'white' + + plot.level = 1 + plot.meshlines = { + 'type': 'tally', + 'id': 1, + 'linewidth': 2, + 'color': (40, 30, 20) + } + return plot + + +def test_attributes(myplot): + assert myplot.name == 'myplot' + + +def test_repr(myplot): + r = repr(myplot) + assert isinstance(r, str) + + +def test_from_geometry(): + width = 25. + s = openmc.Sphere(R=width/2, boundary_type='vacuum') + c = openmc.Cell(region=-s) + univ = openmc.Universe(cells=[c]) + geom = openmc.Geometry(univ) + + for basis in ('xy', 'yz', 'xz'): + plot = openmc.Plot.from_geometry(geom, basis) + assert plot.origin == pytest.approx((0., 0., 0.)) + assert plot.width == pytest.approx((width, width)) + + +def test_highlight_domains(): + plot = openmc.Plot() + plot.color_by = 'material' + plots = openmc.Plots([plot]) + + model = openmc.examples.pwr_pin_cell() + mats = {m for m in model.materials if 'UO2' in m.name} + plots.highlight_domains(model.geometry, mats) + + +def test_to_xml_element(myplot): + elem = myplot.to_xml_element() + assert 'id' in elem.attrib + assert 'color_by' in elem.attrib + assert 'type' in elem.attrib + assert elem.find('origin') is not None + assert elem.find('width') is not None + assert elem.find('pixels') is not None + assert elem.find('background').text == '0 0 0' + + +def test_plots(run_in_tmpdir): + p1 = openmc.Plot(name='plot1') + p2 = openmc.Plot(name='plot2') + plots = openmc.Plots([p1, p2]) + assert len(plots) == 2 + + p3 = openmc.Plot(name='plot3') + plots.append(p3) + assert len(plots) == 3 + + plots.export_to_xml() From ebd4f72b4075f17ed7f33f2b18e4f6a8318346df Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 31 Jan 2018 13:13:15 -0600 Subject: [PATCH 063/212] Update installation instructions for Python API --- docs/source/devguide/workflow.rst | 22 ++++++++ docs/source/quickinstall.rst | 24 +++++---- docs/source/usersguide/install.rst | 85 ++++++++++++++++++++++-------- 3 files changed, 101 insertions(+), 30 deletions(-) diff --git a/docs/source/devguide/workflow.rst b/docs/source/devguide/workflow.rst index fd1ae0455e..9b27fd655f 100644 --- a/docs/source/devguide/workflow.rst +++ b/docs/source/devguide/workflow.rst @@ -103,6 +103,27 @@ changes you've made in your private repository back to mit-crpg/openmc repository, simply follow the steps above with an extra step of pulling a branch from your private repository into a public fork. +.. _devguide_editable: + +Working in "Development" Mode +----------------------------- + +If you are making changes to the Python API during development, it is highly +suggested to install the Python API in development/editable mode using +pip_. From the root directory of the OpenMC repository, run: + +.. code-block:: sh + + pip install -e .[test] + +This installs the OpenMC Python package in `"editable" mode +`_ so +that 1) it can be imported from a Python interpreter and 2) any changes made are +immediately reflected in the installed version (that is, you don't need to keep +reinstalling it). While the same effect can be achieved using the +:envvar:`PYTHONPATH` environment variable, this is generally discouraged as it +can interfere with virtual environments. + .. _git: http://git-scm.com/ .. _GitHub: https://github.com/ .. _git flow: http://nvie.com/git-model @@ -114,3 +135,4 @@ from your private repository into a public fork. .. _Bitbucket: https://bitbucket.org .. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html .. _NNDC: http://www.nndc.bnl.gov/endf/b7.1/acefiles.html +.. _pip: https://pip.pypa.io/en/stable/ diff --git a/docs/source/quickinstall.rst b/docs/source/quickinstall.rst index 97980037c5..7176b67be0 100644 --- a/docs/source/quickinstall.rst +++ b/docs/source/quickinstall.rst @@ -57,7 +57,6 @@ are no longer supported. .. _Personal Package Archive: https://launchpad.net/~paulromano/+archive/staging .. _APT package manager: https://help.ubuntu.com/community/AptGet/Howto -.. _HDF5: http://www.hdfgroup.org/HDF5/ --------------------------------------- Installing from Source on Ubuntu 15.04+ @@ -83,9 +82,12 @@ building and installing OpenMC from source. Installing from Source on Linux or Mac OS X ------------------------------------------- -All OpenMC source code is hosted on GitHub_. If you have git_, the gfortran_ -compiler, CMake_, and HDF5_ installed, you can download and install OpenMC be -entering the following commands in a terminal: +All OpenMC source code is hosted on `GitHub +`_. If you have `git +`_, the `gcc `_ compiler suite, +`CMake `_, and `HDF5 `_ +installed, you can download and install OpenMC be entering the following +commands in a terminal: .. code-block:: sh @@ -104,11 +106,15 @@ should specify an installation directory where you have write access, e.g. cmake -DCMAKE_INSTALL_PREFIX=$HOME/.local .. +The :mod:`openmc` Python package must be installed separately. The easiest way +to install it is using `pip `_, which is +included by default in Python 2.7 and Python 3.4+. From the root directory of +the OpenMC distribution/repository, run: + +.. code-block:: sh + + pip install . + If you want to build a parallel version of OpenMC (using OpenMP or MPI), directions can be found in the :ref:`detailed installation instructions `. - -.. _GitHub: https://github.com/mit-crpg/openmc -.. _git: http://git-scm.com -.. _gfortran: http://gcc.gnu.org/wiki/GFortran -.. _CMake: http://www.cmake.org diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 6bb685f480..48188928cf 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -6,17 +6,18 @@ Installation and Configuration .. currentmodule:: openmc +.. _install_conda: + ---------------------------------------- Installing on Linux/Mac with conda-forge ---------------------------------------- -`Conda `_ is an open source package management -system and environment management system for installing multiple versions of -software packages and their dependencies and switching easily between -them. `conda-forge `_ is a community-led conda -channel of installable packages. For instructions on installing conda, please -consult their `documentation -`_. +Conda_ is an open source package management system and environment management +system for installing multiple versions of software packages and their +dependencies and switching easily between them. `conda-forge +`_ is a community-led conda channel of +installable packages. For instructions on installing conda, please consult their +`documentation `_. Once you have `conda` installed on your system, add the `conda-forge` channel to your configuration with: @@ -38,6 +39,8 @@ It is possible to list all of the versions of OpenMC available on your platform conda search openmc --channel conda-forge +.. _install_ppa: + ----------------------------- Installing on Ubuntu with PPA ----------------------------- @@ -68,9 +71,11 @@ are no longer supported. .. _Personal Package Archive: https://launchpad.net/~paulromano/+archive/staging .. _APT package manager: https://help.ubuntu.com/community/AptGet/Howto --------------------- -Building from Source --------------------- +.. _install_source: + +---------------------- +Installing from Source +---------------------- .. _prerequisites: @@ -191,8 +196,8 @@ switch to the source of the latest stable release, run the following commands:: git checkout master .. _GitHub: https://github.com/mit-crpg/openmc -.. _git: http://git-scm.com -.. _ssh: http://en.wikipedia.org/wiki/Secure_Shell +.. _git: https://git-scm.com +.. _ssh: https://en.wikipedia.org/wiki/Secure_Shell .. _usersguide_build: @@ -366,16 +371,52 @@ To run the test suite, you will first need to download a pre-generated cross section library along with windowed multipole data. Please refer to our :ref:`devguide_tests` documentation for further details. --------------------- -Python Prerequisites --------------------- +--------------------- +Installing Python API +--------------------- -OpenMC's :ref:`Python API ` works with either Python 2.7 or Python -3.2+. In addition to Python itself, the API relies on a number of third-party -packages. All prerequisites can be installed using `conda -`_ (recommended), `pip -`_, or through the package manager in most Linux -distributions. +If you installed OpenMC using :ref:`Conda ` or :ref:`PPA +`, no further steps are necessary in order to use OpenMC's +:ref:`Python API `. However, if you are :ref:`installing from source +`, the Python API is not installed by default when ``make +install`` is run because in many situations it doesn't make sense to install a +Python package in the same location as the ``openmc`` executable (for example, +if you are installing the package into a `virtual environment +`_). The easiest way to install +the :mod:`openmc` Python package is to use pip_, which is included by default in +Python 2.7 and Python 3.4+. From the root directory of the OpenMC +distribution/repository, run: + +.. code-block:: sh + + pip install . + +pip will first check that all :ref:`required third-party packages +` have been installed, and if they are not present, +they will be installed by downloading the appropriate packages from the Python +Package Index (`PyPI `_). However, do note that since pip +runs the ``setup.py`` script which requires NumPy, you will have to first +install NumPy: + +.. code-block:: sh + + pip install numpy + +Installing in "Development" Mode +-------------------------------- + +If you are primarily doing development with OpenMC, it is strongly recommended +to install the Python package in :ref:`"editable" mode `. + +.. _usersguide_python_prereqs: + +Prerequisites +------------- + +The Python API works with either Python 2.7 or Python 3.2+. In addition to +Python itself, the API relies on a number of third-party packages. All +prerequisites can be installed using Conda_ (recommended), pip_, or through the +package manager in most Linux distributions. .. admonition:: Required :class: error @@ -457,3 +498,5 @@ schemas.xml file in your own OpenMC source directory. .. _RELAX NG: http://relaxng.org/ .. _NNDC: http://www.nndc.bnl.gov/endf/b7.1/acefiles.html .. _ctest: http://www.cmake.org/cmake/help/v2.8.12/ctest.html +.. _Conda: https://conda.io/docs/ +.. _pip: https://pip.pypa.io/en/stable/ From bf8c556b5afea43be0973ec1af6514e1d4b24d87 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 31 Jan 2018 16:17:42 -0600 Subject: [PATCH 064/212] Unit tests for openmc.Cell --- openmc/cell.py | 9 +- tests/unit_tests/__init__.py | 9 ++ tests/unit_tests/conftest.py | 31 +++++ tests/unit_tests/test_cell.py | 204 ++++++++++++++++++++++++++++++ tests/unit_tests/test_material.py | 40 +----- tests/unit_tests/test_region.py | 8 +- 6 files changed, 252 insertions(+), 49 deletions(-) create mode 100644 tests/unit_tests/test_cell.py diff --git a/openmc/cell.py b/openmc/cell.py index 5975d7f70b..074fadc06d 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -211,14 +211,7 @@ class Cell(IDManagerMixin): @fill.setter def fill(self, fill): if fill is not None: - if isinstance(fill, string_types): - if fill.strip().lower() != 'void': - msg = 'Unable to set Cell ID="{0}" to use a non-Material ' \ - 'or Universe fill "{1}"'.format(self._id, fill) - raise ValueError(msg) - fill = None - - elif isinstance(fill, Iterable): + if isinstance(fill, Iterable): for i, f in enumerate(fill): if f is not None: cv.check_type('cell.fill[i]', f, openmc.Material) diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py index e69de29bb2..59a520c12a 100644 --- a/tests/unit_tests/__init__.py +++ b/tests/unit_tests/__init__.py @@ -0,0 +1,9 @@ +import numpy as np +import pytest + + +def assert_unbounded(obj): + """Assert that a region/cell is unbounded.""" + ll, ur = obj.bounding_box + assert ll == pytest.approx((-np.inf, -np.inf, -np.inf)) + assert ur == pytest.approx((np.inf, np.inf, np.inf)) diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index aad0ac0581..334bb5fb95 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -1,3 +1,4 @@ +import openmc import pytest @@ -8,3 +9,33 @@ def run_in_tmpdir(tmpdir): yield finally: orig.chdir() + + +@pytest.fixture(scope='module') +def uo2(): + m = openmc.Material(material_id=100, name='UO2') + m.add_nuclide('U235', 1.0) + m.add_nuclide('O16', 2.0) + m.set_density('g/cm3', 10.0) + m.depletable = True + return m + + +@pytest.fixture(scope='module') +def sphere_model(): + model = openmc.model.Model() + + m = openmc.Material() + m.add_nuclide('U235', 1.0) + m.set_density('g/cm3', 1.0) + model.materials.append(m) + + sph = openmc.Sphere(boundary_type='vacuum') + c = openmc.Cell(fill=m, region=-sph) + model.geometry.root_universe = openmc.Universe(cells=[c]) + + model.settings.particles = 100 + model.settings.batches = 10 + model.settings.run_mode = 'fixed source' + model.settings.source = openmc.Source(space=openmc.stats.Point()) + return model diff --git a/tests/unit_tests/test_cell.py b/tests/unit_tests/test_cell.py new file mode 100644 index 0000000000..6e6483a28e --- /dev/null +++ b/tests/unit_tests/test_cell.py @@ -0,0 +1,204 @@ +import xml.etree. ElementTree as ET + +import numpy as np +import openmc +import pytest + +from tests.unit_tests import assert_unbounded + + +@pytest.fixture +def cell_with_lattice(): + m_inside = [openmc.Material(), openmc.Material(), None, openmc.Material()] + m_outside = openmc.Material() + + cyl = openmc.ZCylinder(R=1.0) + inside_cyl = openmc.Cell(fill=m_inside, region=-cyl) + outside_cyl = openmc.Cell(fill=m_outside, region=+cyl) + univ = openmc.Universe(cells=[inside_cyl, outside_cyl]) + + lattice = openmc.RectLattice() + lattice.lower_left = (-4.0, -4.0) + lattice.pitch = (4.0, 4.0) + lattice.dimension = (2, 2) + lattice.universes = [[univ, univ], [univ, univ]] + main_cell = openmc.Cell(fill=lattice) + + return ([inside_cyl, outside_cyl, main_cell], + [m_inside[0], m_inside[1], m_inside[3], m_outside], + univ, lattice) + + +def test_contains(): + # Cell with specified region + s = openmc.XPlane() + c = openmc.Cell(region=+s) + assert (1.0, 0.0, 0.0) in c + assert (-1.0, 0.0, 0.0) not in c + + # Cell with no region + c = openmc.Cell() + assert (10.0, -4., 2.0) in c + + +def test_repr(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + repr(cells[0]) # cell with distributed materials + repr(cells[1]) # cell with material + repr(cells[2]) # cell with lattice + + # Empty cell + c = openmc.Cell() + repr(c) + + +def test_bounding_box(): + zcyl = openmc.ZCylinder() + c = openmc.Cell(region=-zcyl) + ll, ur = c.bounding_box + assert ll == pytest.approx((-1., -1., -np.inf)) + assert ur == pytest.approx((1., 1., np.inf)) + + # Cell with no region specified + c = openmc.Cell() + assert_unbounded(c) + + +def test_clone(): + m = openmc.Material() + cyl = openmc.ZCylinder() + c = openmc.Cell(fill=m, region=-cyl) + c.temperature = 650. + + c2 = c.clone() + assert c2.id != c.id + assert c2.fill != c.fill + assert c2.region != c.region + assert c2.temperature == c.temperature + + +def test_temperature(cell_with_lattice): + # Make sure temperature propagates through universes + m = openmc.Material() + s = openmc.XPlane() + c1 = openmc.Cell(fill=m, region=+s) + c2 = openmc.Cell(fill=m, region=-s) + u1 = openmc.Universe(cells=[c1, c2]) + c = openmc.Cell(fill=u1) + + c.temperature = 400.0 + assert c1.temperature == 400.0 + assert c2.temperature == 400.0 + with pytest.raises(ValueError): + c.temperature = -100. + + # distributed temperature + cells, _, _, _ = cell_with_lattice + c = cells[0] + c.temperature = (300., 600., 900.) + + +def test_rotation(): + u = openmc.Universe() + c = openmc.Cell(fill=u) + c.rotation = (180.0, 0.0, 0.0) + assert np.allclose(c.rotation_matrix, [ + [1., 0., 0.], + [0., -1., 0.], + [0., 0., -1.] + ]) + + c.rotation = (0.0, 90.0, 0.0) + assert np.allclose(c.rotation_matrix, [ + [0., 0., -1.], + [0., 1., 0.], + [1., 0., 0.] + ]) + + +def test_volume(run_in_tmpdir, sphere_model): + """Test adding volume information from a volume calculation.""" + ll, ur = sphere_model.geometry.bounding_box + cells = list(sphere_model.geometry.root_universe.cells.values()) + sphere_model.settings.volume_calculations = [ + openmc.VolumeCalculation(domains=cells, samples=1000, + lower_left=ll, upper_right=ur) + ] + sphere_model.export_to_xml() + openmc.calculate_volumes() + volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') + cells[0].add_volume_information(volume_calc) + + +def test_get_nuclides(uo2): + c = openmc.Cell(fill=uo2) + nucs = c.get_nuclides() + assert nucs == ['U235', 'O16'] + + +def test_nuclide_densities(uo2): + c = openmc.Cell(fill=uo2) + expected_nucs = ['U235', 'O16'] + expected_density = [1.0, 2.0] + tuples = list(c.get_nuclide_densities().values()) + for nuc, density, t in zip(expected_nucs, expected_density, tuples): + assert nuc == t[0] + assert density == t[1] + + # Empty cell + c = openmc.Cell() + assert not c.get_nuclide_densities() + + +def test_get_all_universes(cell_with_lattice): + # Cell with nested universes + c1 = openmc.Cell() + u1 = openmc.Universe(cells=[c1]) + c2 = openmc.Cell(fill=u1) + u2 = openmc.Universe(cells=[c2]) + c3 = openmc.Cell(fill=u2) + univs = set(c3.get_all_universes().values()) + assert not (univs ^ {u1, u2}) + + # Cell with lattice + cells, mats, univ, lattice = cell_with_lattice + univs = set(cells[-1].get_all_universes().values()) + assert not (univs ^ {univ}) + + +def test_get_all_materials(cell_with_lattice): + # Normal cell + m = openmc.Material() + c = openmc.Cell(fill=m) + test_mats = set(c.get_all_materials().values()) + assert not(test_mats ^ {m}) + + # Cell filled with distributed materials + cells, mats, univ, lattice = cell_with_lattice + c = cells[0] + test_mats = set(c.get_all_materials().values()) + assert not (test_mats ^ set(m for m in c.fill if m is not None)) + + # Cell filled with universe + c = cells[-1] + test_mats = set(c.get_all_materials().values()) + assert not (test_mats ^ set(mats)) + + +def test_to_xml_element(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + + c = cells[-1] + root = ET.Element('geometry') + elem = c.create_xml_subelement(root) + assert elem.tag == 'cell' + assert elem.get('id') == str(c.id) + assert elem.get('region') is None + surf_elem = root.find('surface') + assert surf_elem.get('id') == str(cells[0].region.surface.id) + + c = cells[0] + c.temperature = 900.0 + elem = c.create_xml_subelement(root) + assert elem.get('region') == str(c.region) + assert elem.get('temperature') == str(c.temperature) diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index b96cbfb4c0..ed2f7698a2 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -5,41 +5,6 @@ import openmc.examples import pytest -@pytest.fixture(scope='module') -def uo2(): - m = openmc.Material(material_id=100, name='UO2') - m.add_nuclide('U235', 1.0) - m.add_nuclide('O16', 2.0) - m.set_density('g/cm3', 10.0) - m.depletable = True - return m - - -@pytest.fixture(scope='module') -def sphere_model(): - model = openmc.model.Model() - - m = openmc.Material() - m.add_nuclide('U235', 1.0) - m.set_density('g/cm3', 1.0) - model.materials.append(m) - - sph = openmc.Sphere(boundary_type='vacuum') - c = openmc.Cell(fill=m, region=-sph) - model.geometry.root_universe = openmc.Universe(cells=[c]) - - model.settings.particles = 100 - model.settings.batches = 10 - model.settings.run_mode = 'fixed source' - model.settings.source = openmc.Source(space=openmc.stats.Point()) - ll, ur = c.region.bounding_box - model.settings.volume_calculations = [ - openmc.VolumeCalculation(domains=[m], samples=1000, - lower_left=ll, upper_right=ur) - ] - return model - - def test_attributes(uo2): assert uo2.name == 'UO2' assert uo2.id == 100 @@ -143,6 +108,11 @@ def test_isotropic(): def test_volume(run_in_tmpdir, sphere_model): """Test adding volume information from a volume calculation.""" + ll, ur = sphere_model.geometry.bounding_box + sphere_model.settings.volume_calculations = [ + openmc.VolumeCalculation(domains=sphere_model.materials, samples=1000, + lower_left=ll, upper_right=ur) + ] sphere_model.export_to_xml() openmc.calculate_volumes() volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') diff --git a/tests/unit_tests/test_region.py b/tests/unit_tests/test_region.py index 346ec7d95e..c4f4065bf3 100644 --- a/tests/unit_tests/test_region.py +++ b/tests/unit_tests/test_region.py @@ -2,18 +2,14 @@ import numpy as np import pytest import openmc +from tests.unit_tests import assert_unbounded + @pytest.fixture def reset(): openmc.reset_auto_ids() -def assert_unbounded(region): - ll, ur = region.bounding_box - assert ll == pytest.approx((-np.inf, -np.inf, -np.inf)) - assert ur == pytest.approx((np.inf, np.inf, np.inf)) - - def test_union(reset): s1 = openmc.XPlane(surface_id=1, x0=5) s2 = openmc.XPlane(surface_id=2, x0=-5) From b573ad50cf26450a7070d606127e74db7d84ba11 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 31 Jan 2018 21:50:29 -0600 Subject: [PATCH 065/212] Add test for Region.from_expression --- tests/unit_tests/test_region.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/unit_tests/test_region.py b/tests/unit_tests/test_region.py index c4f4065bf3..377c8fbd58 100644 --- a/tests/unit_tests/test_region.py +++ b/tests/unit_tests/test_region.py @@ -128,3 +128,35 @@ def test_extend_clone(): r5 = ~r1 r6 = r5.clone() + + +def test_from_expression(reset): + # Create surface dictionary + s1 = openmc.ZCylinder(surface_id=1) + s2 = openmc.ZPlane(surface_id=2, z0=-10.) + s3 = openmc.ZPlane(surface_id=3, z0=10.) + surfs = {1: s1, 2: s2, 3: s3} + + r = openmc.Region.from_expression('-1 2 -3', surfs) + assert isinstance(r, openmc.Intersection) + assert r[:] == [-s1, +s2, -s3] + + r = openmc.Region.from_expression('+1 | -2 | +3', surfs) + assert isinstance(r, openmc.Union) + assert r[:] == [+s1, -s2, +s3] + + r = openmc.Region.from_expression('~(-1)', surfs) + assert r == +s1 + + # Since & has higher precendence than |, the resulting region should be an + # instance of Union + r = openmc.Region.from_expression('1 -2 | 3', surfs) + assert isinstance(r, openmc.Union) + assert isinstance(r[0], openmc.Intersection) + assert r[0][:] == [+s1, -s2] + + # ...but not if we use parentheses + r = openmc.Region.from_expression('1 (-2 | 3)', surfs) + assert isinstance(r, openmc.Intersection) + assert isinstance(r[1], openmc.Union) + assert r[1][:] == [-s2, +s3] From 1a93883b670421e37ac226849df8dfc98abed0fb Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 07:17:34 -0600 Subject: [PATCH 066/212] Add tests for openmc.Universe --- openmc/universe.py | 8 +- tests/unit_tests/conftest.py | 22 ++++ tests/unit_tests/test_cell.py | 22 ---- tests/unit_tests/test_geometry.py | 17 ++++ tests/unit_tests/test_universe.py | 160 ++++++++++++++++++++++++++++++ 5 files changed, 203 insertions(+), 26 deletions(-) create mode 100644 tests/unit_tests/test_geometry.py create mode 100644 tests/unit_tests/test_universe.py diff --git a/openmc/universe.py b/openmc/universe.py index 92b152ca09..4a0a1a9aac 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -92,7 +92,7 @@ class Universe(IDManagerMixin): return openmc.Union(regions).bounding_box else: # Infinite bounding box - return openmc.Intersection().bounding_box + return openmc.Intersection([]).bounding_box @name.setter def name(self, name): @@ -322,7 +322,7 @@ class Universe(IDManagerMixin): if not isinstance(cell, openmc.Cell): msg = 'Unable to add a Cell to Universe ID="{0}" since "{1}" is not ' \ 'a Cell'.format(self._id, cell) - raise ValueError(msg) + raise TypeError(msg) cell_id = cell.id @@ -342,7 +342,7 @@ class Universe(IDManagerMixin): if not isinstance(cells, Iterable): msg = 'Unable to add Cells to Universe ID="{0}" since "{1}" is not ' \ 'iterable'.format(self._id, cells) - raise ValueError(msg) + raise TypeError(msg) for cell in cells: self.add_cell(cell) @@ -360,7 +360,7 @@ class Universe(IDManagerMixin): if not isinstance(cell, openmc.Cell): msg = 'Unable to remove a Cell from Universe ID="{0}" since "{1}" is ' \ 'not a Cell'.format(self._id, cell) - raise ValueError(msg) + raise TypeError(msg) # If the Cell is in the Universe's list of Cells, delete it if cell.id in self._cells: diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index 334bb5fb95..6210064719 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -39,3 +39,25 @@ def sphere_model(): model.settings.run_mode = 'fixed source' model.settings.source = openmc.Source(space=openmc.stats.Point()) return model + + +@pytest.fixture +def cell_with_lattice(): + m_inside = [openmc.Material(), openmc.Material(), None, openmc.Material()] + m_outside = openmc.Material() + + cyl = openmc.ZCylinder(R=1.0) + inside_cyl = openmc.Cell(fill=m_inside, region=-cyl) + outside_cyl = openmc.Cell(fill=m_outside, region=+cyl) + univ = openmc.Universe(cells=[inside_cyl, outside_cyl]) + + lattice = openmc.RectLattice() + lattice.lower_left = (-4.0, -4.0) + lattice.pitch = (4.0, 4.0) + lattice.dimension = (2, 2) + lattice.universes = [[univ, univ], [univ, univ]] + main_cell = openmc.Cell(fill=lattice) + + return ([inside_cyl, outside_cyl, main_cell], + [m_inside[0], m_inside[1], m_inside[3], m_outside], + univ, lattice) diff --git a/tests/unit_tests/test_cell.py b/tests/unit_tests/test_cell.py index 6e6483a28e..b9470a3a6f 100644 --- a/tests/unit_tests/test_cell.py +++ b/tests/unit_tests/test_cell.py @@ -7,28 +7,6 @@ import pytest from tests.unit_tests import assert_unbounded -@pytest.fixture -def cell_with_lattice(): - m_inside = [openmc.Material(), openmc.Material(), None, openmc.Material()] - m_outside = openmc.Material() - - cyl = openmc.ZCylinder(R=1.0) - inside_cyl = openmc.Cell(fill=m_inside, region=-cyl) - outside_cyl = openmc.Cell(fill=m_outside, region=+cyl) - univ = openmc.Universe(cells=[inside_cyl, outside_cyl]) - - lattice = openmc.RectLattice() - lattice.lower_left = (-4.0, -4.0) - lattice.pitch = (4.0, 4.0) - lattice.dimension = (2, 2) - lattice.universes = [[univ, univ], [univ, univ]] - main_cell = openmc.Cell(fill=lattice) - - return ([inside_cyl, outside_cyl, main_cell], - [m_inside[0], m_inside[1], m_inside[3], m_outside], - univ, lattice) - - def test_contains(): # Cell with specified region s = openmc.XPlane() diff --git a/tests/unit_tests/test_geometry.py b/tests/unit_tests/test_geometry.py new file mode 100644 index 0000000000..fc681c8d8c --- /dev/null +++ b/tests/unit_tests/test_geometry.py @@ -0,0 +1,17 @@ +import xml.etree.ElementTree as ET + +import openmc +import pytest + + +def test_determine_paths(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + u = openmc.Universe(cells=[cells[-1]]) + geom = openmc.Geometry(u) + + geom.determine_paths() + assert len(cells[0].paths) == 4 + assert len(cells[1].paths) == 4 + assert len(cells[2].paths) == 1 + assert len(mats[0].paths) == 1 + assert len(mats[-1].paths) == 4 diff --git a/tests/unit_tests/test_universe.py b/tests/unit_tests/test_universe.py new file mode 100644 index 0000000000..656b419cf0 --- /dev/null +++ b/tests/unit_tests/test_universe.py @@ -0,0 +1,160 @@ +import xml.etree.ElementTree as ET + +import numpy as np +import openmc +import pytest + +from tests.unit_tests import assert_unbounded + + +def test_basic(): + c1 = openmc.Cell() + c2 = openmc.Cell() + c3 = openmc.Cell() + u = openmc.Universe(name='cool', cells=(c1, c2, c3)) + assert u.name == 'cool' + + cells = set(u.cells.values()) + assert not (cells ^ {c1, c2, c3}) + + # Test __repr__ + repr(u) + + with pytest.raises(TypeError): + u.add_cell(openmc.Material()) + with pytest.raises(TypeError): + u.add_cells(c1) + + u.remove_cell(c3) + cells = set(u.cells.values()) + assert not (cells ^ {c1, c2}) + + u.clear_cells() + assert not set(u.cells) + + +def test_bounding_box(): + cyl1 = openmc.ZCylinder(R=1.0) + cyl2 = openmc.ZCylinder(R=2.0) + c1 = openmc.Cell(region=-cyl1) + c2 = openmc.Cell(region=+cyl1 & -cyl2) + + u = openmc.Universe(cells=[c1, c2]) + ll, ur = u.bounding_box + assert ll == pytest.approx((-2., -2., -np.inf)) + assert ur == pytest.approx((2., 2., np.inf)) + + u = openmc.Universe() + assert_unbounded(u) + + +def test_find(uo2): + xp = openmc.XPlane() + c1 = openmc.Cell(fill=uo2, region=+xp) + c2 = openmc.Cell(region=-xp) + u1 = openmc.Universe(cells=(c1, c2)) + + cyl = openmc.ZCylinder() + c3 = openmc.Cell(fill=u1, region=-cyl) + c4 = openmc.Cell(region=+cyl) + u = openmc.Universe(cells=(c3, c4)) + + seq = u.find((0.5, 0., 0.)) + assert seq[-1] == c1 + seq = u.find((-0.5, 0., 0.)) + assert seq[-1] == c2 + seq = u.find((-1.5, 0., 0.)) + assert seq[-1] == c4 + + +def test_volume(run_in_tmpdir, sphere_model): + """Test adding volume information from a volume calculation.""" + univ = sphere_model.geometry.root_universe + ll, ur = univ.bounding_box + sphere_model.settings.volume_calculations = [ + openmc.VolumeCalculation(domains=[univ], samples=1000, + lower_left=ll, upper_right=ur) + ] + sphere_model.export_to_xml() + openmc.calculate_volumes() + volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') + univ.add_volume_information(volume_calc) + + # get_nuclide_densities relies on volume information + nucs = set(univ.get_nuclide_densities()) + assert not (nucs ^ {'U235'}) + + +def test_plot(run_in_tmpdir, sphere_model): + m = sphere_model.materials[0] + univ = sphere_model.geometry.root_universe + + colors = {m: 'limegreen'} + for basis in ('xy', 'yz', 'xz'): + univ.plot( + basis=basis, + pixels=(10, 10), + color_by='material', + colors=colors, + filename='test.png' + ) + + +def test_get_nuclides(uo2): + c = openmc.Cell(fill=uo2) + univ = openmc.Universe(cells=[c]) + nucs = univ.get_nuclides() + assert nucs == ['U235', 'O16'] + + +def test_cells(): + cells = [openmc.Cell() for i in range(5)] + cells2 = [openmc.Cell() for i in range(3)] + cells[0].fill = openmc.Universe(cells=cells2) + u = openmc.Universe(cells=cells) + assert not (set(u.cells.values()) ^ set(cells)) + + all_cells = set(u.get_all_cells().values()) + assert not (all_cells ^ set(cells + cells2)) + + +def test_get_all_materials(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + test_mats = set(univ.get_all_materials().values()) + assert not (test_mats ^ set(mats)) + + +def test_get_all_universes(): + c1 = openmc.Cell() + u1 = openmc.Universe(cells=[c1]) + c2 = openmc.Cell() + u2 = openmc.Universe(cells=[c2]) + c3 = openmc.Cell(fill=u1) + c4 = openmc.Cell(fill=u2) + u3 = openmc.Universe(cells=[c3, c4]) + + univs = set(u3.get_all_universes().values()) + assert not (univs ^ {u1, u2}) + + +def test_clone(): + c1 = openmc.Cell() + c2 = openmc.Cell() + u = openmc.Universe(cells=[c1, c2]) + + u_clone = u.clone() + assert u_clone.id != u.id + assert not (set(u.cells) & set(u_clone.cells)) + + +def test_create_xml(cell_with_lattice): + cells = [openmc.Cell() for i in range(5)] + u = openmc.Universe(cells=cells) + + geom = ET.Element('geom') + u.create_xml_subelement(geom) + cell_elems = geom.findall('cell') + assert len(cell_elems) == len(cells) + assert all(c.get('universe') == str(u.id) for c in cell_elems) + assert not (set(c.get('id') for c in cell_elems) ^ + set(str(c.id) for c in cells)) From 347243876f5c6d50a13acaa13a136dc57eb3f536 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 10:00:50 -0600 Subject: [PATCH 067/212] Combine volume calculations into a single unit test --- tests/unit_tests/test_cell.py | 14 ----- tests/unit_tests/test_geometry.py | 98 +++++++++++++++++++++++++++++++ tests/unit_tests/test_material.py | 13 ---- tests/unit_tests/test_universe.py | 18 ------ 4 files changed, 98 insertions(+), 45 deletions(-) diff --git a/tests/unit_tests/test_cell.py b/tests/unit_tests/test_cell.py index b9470a3a6f..d01d94a324 100644 --- a/tests/unit_tests/test_cell.py +++ b/tests/unit_tests/test_cell.py @@ -94,20 +94,6 @@ def test_rotation(): ]) -def test_volume(run_in_tmpdir, sphere_model): - """Test adding volume information from a volume calculation.""" - ll, ur = sphere_model.geometry.bounding_box - cells = list(sphere_model.geometry.root_universe.cells.values()) - sphere_model.settings.volume_calculations = [ - openmc.VolumeCalculation(domains=cells, samples=1000, - lower_left=ll, upper_right=ur) - ] - sphere_model.export_to_xml() - openmc.calculate_volumes() - volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') - cells[0].add_volume_information(volume_calc) - - def test_get_nuclides(uo2): c = openmc.Cell(fill=uo2) nucs = c.get_nuclides() diff --git a/tests/unit_tests/test_geometry.py b/tests/unit_tests/test_geometry.py index fc681c8d8c..8394537873 100644 --- a/tests/unit_tests/test_geometry.py +++ b/tests/unit_tests/test_geometry.py @@ -4,6 +4,104 @@ import openmc import pytest +def test_volume(uo2): + """Test adding volume information from a volume calculation.""" + # Create model with nested spheres + model = openmc.model.Model() + model.materials.append(uo2) + inner = openmc.Sphere(R=1.) + outer = openmc.Sphere(R=2., boundary_type='vacuum') + c1 = openmc.Cell(fill=uo2, region=-inner) + c2 = openmc.Cell(region=+inner & -outer) + u = openmc.Universe(cells=[c1, c2]) + model.geometry.root_universe = u + model.settings.particles = 100 + model.settings.batches = 10 + model.settings.run_mode = 'fixed source' + model.settings.source = openmc.Source(space=openmc.stats.Point()) + + ll, ur = model.geometry.bounding_box + assert ll == pytest.approx((-outer.r, -outer.r, -outer.r)) + assert ur == pytest.approx((outer.r, outer.r, outer.r)) + model.settings.volume_calculations + + for domain in (c1, uo2, u): + # Run stochastic volume calculation + volume_calc = openmc.VolumeCalculation( + domains=[domain], samples=1000, lower_left=ll, upper_right=ur) + model.settings.volume_calculations = [volume_calc] + model.export_to_xml() + openmc.calculate_volumes() + + # Load results and add volume information + volume_calc.load_results('volume_1.h5') + model.geometry.add_volume_information(volume_calc) + + # get_nuclide_densities relies on volume information + nucs = set(domain.get_nuclide_densities()) + assert not (nucs ^ {'U235', 'O16'}) + + +def test_export_xml(): + pass + + +def test_find(): + pass + + +def test_get_instances(): + pass + + +def test_get_all_universes(): + pass + + +def test_get_all_materials(): + pass + + +def test_get_all_material_cells(): + pass + + +def test_get_all_material_universes(): + pass + + +def test_get_all_lattices(): + pass + + +def test_get_all_surfaces(): + pass + + +def test_get_materials_by_name(): + pass + + +def test_get_cells_by_name(): + pass + + +def test_get_cells_by_fill_name(): + pass + + +def test_get_universes_by_name(): + pass + + +def test_get_lattices_by_name(): + pass + + +def test_clone(): + pass + + def test_determine_paths(cell_with_lattice): cells, mats, univ, lattice = cell_with_lattice u = openmc.Universe(cells=[cells[-1]]) diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index ed2f7698a2..e92a2ac088 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -106,19 +106,6 @@ def test_isotropic(): assert m2.isotropic == ['H1'] -def test_volume(run_in_tmpdir, sphere_model): - """Test adding volume information from a volume calculation.""" - ll, ur = sphere_model.geometry.bounding_box - sphere_model.settings.volume_calculations = [ - openmc.VolumeCalculation(domains=sphere_model.materials, samples=1000, - lower_left=ll, upper_right=ur) - ] - sphere_model.export_to_xml() - openmc.calculate_volumes() - volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') - sphere_model.materials[0].add_volume_information(volume_calc) - - def test_get_nuclide_densities(uo2): nucs = uo2.get_nuclide_densities() for nuc, density, density_type in nucs.values(): diff --git a/tests/unit_tests/test_universe.py b/tests/unit_tests/test_universe.py index 656b419cf0..ac384e9e46 100644 --- a/tests/unit_tests/test_universe.py +++ b/tests/unit_tests/test_universe.py @@ -67,24 +67,6 @@ def test_find(uo2): assert seq[-1] == c4 -def test_volume(run_in_tmpdir, sphere_model): - """Test adding volume information from a volume calculation.""" - univ = sphere_model.geometry.root_universe - ll, ur = univ.bounding_box - sphere_model.settings.volume_calculations = [ - openmc.VolumeCalculation(domains=[univ], samples=1000, - lower_left=ll, upper_right=ur) - ] - sphere_model.export_to_xml() - openmc.calculate_volumes() - volume_calc = openmc.VolumeCalculation.from_hdf5('volume_1.h5') - univ.add_volume_information(volume_calc) - - # get_nuclide_densities relies on volume information - nucs = set(univ.get_nuclide_densities()) - assert not (nucs ^ {'U235'}) - - def test_plot(run_in_tmpdir, sphere_model): m = sphere_model.materials[0] univ = sphere_model.geometry.root_universe From b9ae59620003f66018c45e7c6566ddf5d4549662 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 11:23:17 -0600 Subject: [PATCH 068/212] Add tests for openmc.Geometry and remove __eq__ on openmc.Lattice --- openmc/geometry.py | 39 +++--- openmc/lattice.py | 19 --- tests/unit_tests/conftest.py | 2 +- tests/unit_tests/test_geometry.py | 199 +++++++++++++++++++++++++----- tests/unit_tests/test_universe.py | 29 ----- 5 files changed, 184 insertions(+), 104 deletions(-) diff --git a/openmc/geometry.py b/openmc/geometry.py index 0738ae615a..ac068e2b04 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -14,8 +14,9 @@ class Geometry(object): Parameters ---------- - root_universe : openmc.Universe, optional - Root universe which contains all others + root : openmc.Universe or Iterable of openmc.Cell, optional + Root universe which contains all others, or an iterable of cells that + should be used to create a root universe. Attributes ---------- @@ -27,11 +28,17 @@ class Geometry(object): """ - def __init__(self, root_universe=None): + def __init__(self, root=None): self._root_universe = None self._offsets = {} - if root_universe is not None: - self.root_universe = root_universe + if root is not None: + if isinstance(root, openmc.Universe): + self.root_universe = root + else: + univ = openmc.Universe() + for cell in root: + univ.add_cell(cell) + self._root_universe = univ @property def root_universe(self): @@ -249,7 +256,7 @@ class Geometry(object): for cell in self.get_all_cells().values(): if cell.fill_type == 'lattice': - if cell.fill not in lattices: + if cell.fill.id not in lattices: lattices[cell.fill.id] = cell.fill return lattices @@ -306,9 +313,7 @@ class Geometry(object): elif not matching and name in material_name: materials.add(material) - materials = list(materials) - materials.sort(key=lambda x: x.id) - return materials + return sorted(materials, key=lambda x: x.id) def get_cells_by_name(self, name, case_sensitive=False, matching=False): """Return a list of cells with matching names. @@ -346,9 +351,7 @@ class Geometry(object): elif not matching and name in cell_name: cells.add(cell) - cells = list(cells) - cells.sort(key=lambda x: x.id) - return cells + return sorted(cells, key=lambda x: x.id) def get_cells_by_fill_name(self, name, case_sensitive=False, matching=False): """Return a list of cells with fills with matching names. @@ -393,9 +396,7 @@ class Geometry(object): elif not matching and name in fill_name: cells.add(cell) - cells = list(cells) - cells.sort(key=lambda x: x.id) - return cells + return sorted(cells, key=lambda x: x.id) def get_universes_by_name(self, name, case_sensitive=False, matching=False): """Return a list of universes with matching names. @@ -433,9 +434,7 @@ class Geometry(object): elif not matching and name in universe_name: universes.add(universe) - universes = list(universes) - universes.sort(key=lambda x: x.id) - return universes + return sorted(universes, key=lambda x: x.id) def get_lattices_by_name(self, name, case_sensitive=False, matching=False): """Return a list of lattices with matching names. @@ -473,9 +472,7 @@ class Geometry(object): elif not matching and name in lattice_name: lattices.add(lattice) - lattices = list(lattices) - lattices.sort(key=lambda x: x.id) - return lattices + return sorted(lattices, key=lambda x: x.id) def determine_paths(self, instances_only=False): """Determine paths through CSG tree for cells and materials. diff --git a/openmc/lattice.py b/openmc/lattice.py index 79f0d43f3b..933f51af34 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -54,25 +54,6 @@ class Lattice(IDManagerMixin): self._outer = None self._universes = None - def __eq__(self, other): - if not isinstance(other, Lattice): - return False - elif self.id != other.id: - return False - elif self.name != other.name: - return False - elif np.any(self.pitch != other.pitch): - return False - elif self.outer != other.outer: - return False - elif np.any(self.universes != other.universes): - return False - else: - return True - - def __ne__(self, other): - return not self == other - @property def name(self): return self._name diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index 6210064719..af534afe35 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -51,7 +51,7 @@ def cell_with_lattice(): outside_cyl = openmc.Cell(fill=m_outside, region=+cyl) univ = openmc.Universe(cells=[inside_cyl, outside_cyl]) - lattice = openmc.RectLattice() + lattice = openmc.RectLattice(name='My Lattice') lattice.lower_left = (-4.0, -4.0) lattice.pitch = (4.0, 4.0) lattice.dimension = (2, 2) diff --git a/tests/unit_tests/test_geometry.py b/tests/unit_tests/test_geometry.py index 8394537873..93d2fa6341 100644 --- a/tests/unit_tests/test_geometry.py +++ b/tests/unit_tests/test_geometry.py @@ -1,10 +1,11 @@ import xml.etree.ElementTree as ET +import numpy as np import openmc import pytest -def test_volume(uo2): +def test_volume(run_in_tmpdir, uo2): """Test adding volume information from a volume calculation.""" # Create model with nested spheres model = openmc.model.Model() @@ -39,67 +40,192 @@ def test_volume(uo2): # get_nuclide_densities relies on volume information nucs = set(domain.get_nuclide_densities()) - assert not (nucs ^ {'U235', 'O16'}) + assert not nucs ^ {'U235', 'O16'} -def test_export_xml(): - pass +def test_export_xml(run_in_tmpdir, uo2): + s1 = openmc.Sphere(R=1.) + s2 = openmc.Sphere(R=2., boundary_type='reflective') + c1 = openmc.Cell(fill=uo2, region=-s1) + c2 = openmc.Cell(fill=uo2, region=+s1 & -s2) + geom = openmc.Geometry([c1, c2]) + geom.export_to_xml() + + doc = ET.parse('geometry.xml') + root = doc.getroot() + assert root.tag == 'geometry' + cells = root.findall('cell') + assert [int(c.get('id')) for c in cells] == [c1.id, c2.id] + surfs = root.findall('surface') + assert [int(s.get('id')) for s in surfs] == [s1.id, s2.id] -def test_find(): - pass +def test_find(uo2): + xp = openmc.XPlane() + c1 = openmc.Cell(fill=uo2, region=+xp) + c2 = openmc.Cell(region=-xp) + u1 = openmc.Universe(cells=(c1, c2)) + + cyl = openmc.ZCylinder() + c3 = openmc.Cell(fill=u1, region=-cyl) + c4 = openmc.Cell(region=+cyl) + geom = openmc.Geometry((c3, c4)) + + seq = geom.find((0.5, 0., 0.)) + assert seq[-1] == c1 + seq = geom.find((-0.5, 0., 0.)) + assert seq[-1] == c2 + seq = geom.find((-1.5, 0., 0.)) + assert seq[-1] == c4 -def test_get_instances(): - pass +def test_get_all_cells(): + cells = [openmc.Cell() for i in range(5)] + cells2 = [openmc.Cell() for i in range(3)] + cells[0].fill = openmc.Universe(cells=cells2) + geom = openmc.Geometry(cells) - -def test_get_all_universes(): - pass + all_cells = set(geom.get_all_cells().values()) + assert not all_cells ^ set(cells + cells2) def test_get_all_materials(): - pass + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_mats = set(geom.get_all_materials().values()) + assert not all_mats ^ {m1, m2} def test_get_all_material_cells(): - pass + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_cells = set(geom.get_all_material_cells().values()) + assert not all_cells ^ {c1, c3} def test_get_all_material_universes(): - pass + m1 = openmc.Material() + m2 = openmc.Material() + c1 = openmc.Cell(fill=m1) + u1 = openmc.Universe(cells=[c1]) + + s = openmc.Sphere() + c2 = openmc.Cell(fill=u1, region=-s) + c3 = openmc.Cell(fill=m2, region=+s) + geom = openmc.Geometry([c2, c3]) + + all_univs = set(geom.get_all_material_universes().values()) + assert not all_univs ^ {u1, geom.root_universe} -def test_get_all_lattices(): - pass +def test_get_all_lattices(cell_with_lattice): + cells, mats, univ, lattice = cell_with_lattice + geom = openmc.Geometry([cells[-1]]) + + lats = list(geom.get_all_lattices().values()) + assert lats == [lattice] -def test_get_all_surfaces(): - pass +def test_get_all_surfaces(uo2): + planes = [openmc.ZPlane(z0=z) for z in np.linspace(-100., 100.)] + slabs = [] + for region in openmc.model.subdivide(planes): + slabs.append(openmc.Cell(fill=uo2, region=region)) + geom = openmc.Geometry(slabs) + + surfs = set(geom.get_all_surfaces().values()) + assert not surfs ^ set(planes) -def test_get_materials_by_name(): - pass +def test_get_by_name(): + m1 = openmc.Material(name='zircaloy') + m1.add_element('Zr', 1.0) + m2 = openmc.Material(name='Zirconium') + m2.add_element('Zr', 1.0) + + c1 = openmc.Cell(fill=m1, name='cell1') + u1 = openmc.Universe(name='Zircaloy universe', cells=[c1]) + + cyl = openmc.ZCylinder() + c2 = openmc.Cell(fill=u1, region=-cyl, name='cell2') + c3 = openmc.Cell(fill=m2, region=+cyl, name='Cell3') + root = openmc.Universe(name='root Universe', cells=[c2, c3]) + geom = openmc.Geometry(root) + + mats = set(geom.get_materials_by_name('zirc')) + assert not mats ^ {m1, m2} + mats = set(geom.get_materials_by_name('zirc', True)) + assert not mats ^ {m1} + mats = set(geom.get_materials_by_name('zirconium', False, True)) + assert not mats ^ {m2} + mats = geom.get_materials_by_name('zirconium', True, True) + assert not mats + + cells = set(geom.get_cells_by_name('cell')) + assert not cells ^ {c1, c2, c3} + cells = set(geom.get_cells_by_name('cell', True)) + assert not cells ^ {c1, c2} + cells = set(geom.get_cells_by_name('cell3', False, True)) + assert not cells ^ {c3} + cells = geom.get_cells_by_name('cell3', True, True) + assert not cells + + cells = set(geom.get_cells_by_fill_name('Zircaloy')) + assert not cells ^ {c1, c2} + cells = set(geom.get_cells_by_fill_name('Zircaloy', True)) + assert not cells ^ {c2} + cells = set(geom.get_cells_by_fill_name('Zircaloy', False, True)) + assert not cells ^ {c1} + cells = geom.get_cells_by_fill_name('Zircaloy', True, True) + assert not cells + + univs = set(geom.get_universes_by_name('universe')) + assert not univs ^ {u1, root} + univs = set(geom.get_universes_by_name('universe', True)) + assert not univs ^ {u1} + univs = set(geom.get_universes_by_name('universe', True, True)) + assert not univs -def test_get_cells_by_name(): - pass +def test_get_lattice_by_name(cell_with_lattice): + cells, _, _, lattice = cell_with_lattice + geom = openmc.Geometry([cells[-1]]) - -def test_get_cells_by_fill_name(): - pass - - -def test_get_universes_by_name(): - pass - - -def test_get_lattices_by_name(): - pass + f = geom.get_lattices_by_name + assert f('lattice') == [lattice] + assert f('lattice', True) == [] + assert f('Lattice', True) == [lattice] + assert f('my lattice', False, True) == [lattice] + assert f('my lattice', True, True) == [] def test_clone(): - pass + c1 = openmc.Cell() + c2 = openmc.Cell() + root = openmc.Universe(cells=[c1, c2]) + geom = openmc.Geometry(root) + + clone = geom.clone() + root_clone = clone.root_universe + + assert root.id != root_clone.id + assert not (set(root.cells) & set(root_clone.cells)) def test_determine_paths(cell_with_lattice): @@ -113,3 +239,8 @@ def test_determine_paths(cell_with_lattice): assert len(cells[2].paths) == 1 assert len(mats[0].paths) == 1 assert len(mats[-1].paths) == 4 + + # Test get_instances + for i in range(4): + assert geom.get_instances(cells[0].paths[i]) == i + assert geom.get_instances(mats[-1].paths[i]) == i diff --git a/tests/unit_tests/test_universe.py b/tests/unit_tests/test_universe.py index ac384e9e46..59e34e2017 100644 --- a/tests/unit_tests/test_universe.py +++ b/tests/unit_tests/test_universe.py @@ -48,25 +48,6 @@ def test_bounding_box(): assert_unbounded(u) -def test_find(uo2): - xp = openmc.XPlane() - c1 = openmc.Cell(fill=uo2, region=+xp) - c2 = openmc.Cell(region=-xp) - u1 = openmc.Universe(cells=(c1, c2)) - - cyl = openmc.ZCylinder() - c3 = openmc.Cell(fill=u1, region=-cyl) - c4 = openmc.Cell(region=+cyl) - u = openmc.Universe(cells=(c3, c4)) - - seq = u.find((0.5, 0., 0.)) - assert seq[-1] == c1 - seq = u.find((-0.5, 0., 0.)) - assert seq[-1] == c2 - seq = u.find((-1.5, 0., 0.)) - assert seq[-1] == c4 - - def test_plot(run_in_tmpdir, sphere_model): m = sphere_model.materials[0] univ = sphere_model.geometry.root_universe @@ -119,16 +100,6 @@ def test_get_all_universes(): assert not (univs ^ {u1, u2}) -def test_clone(): - c1 = openmc.Cell() - c2 = openmc.Cell() - u = openmc.Universe(cells=[c1, c2]) - - u_clone = u.clone() - assert u_clone.id != u.id - assert not (set(u.cells) & set(u_clone.cells)) - - def test_create_xml(cell_with_lattice): cells = [openmc.Cell() for i in range(5)] u = openmc.Universe(cells=cells) From ef16a6cb575e9f907a2c2babc091aca5d9c7d86d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 12:35:29 -0600 Subject: [PATCH 069/212] Fix bug in stochastic volume calculation with void cell --- src/volume_calc.F90 | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/volume_calc.F90 b/src/volume_calc.F90 index 15c0497699..e374f21064 100644 --- a/src/volume_calc.F90 +++ b/src/volume_calc.F90 @@ -193,11 +193,13 @@ contains if (this % domain_type == FILTER_MATERIAL) then i_material = p % material - do i_domain = 1, size(this % domain_id) - if (materials(i_material) % id == this % domain_id(i_domain)) then - call check_hit(i_domain, i_material, indices, hits, n_mat) - end if - end do + if (i_material /= MATERIAL_VOID) then + do i_domain = 1, size(this % domain_id) + if (materials(i_material) % id == this % domain_id(i_domain)) then + call check_hit(i_domain, i_material, indices, hits, n_mat) + end if + end do + end if elseif (this % domain_type == FILTER_CELL) THEN do level = 1, p % n_coord From 07d853dd1d1275eea957095d2fd8a8d7d8148561 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 12:40:54 -0600 Subject: [PATCH 070/212] Allow tests that require GUI (matplotlib) --- .travis.yml | 1 + tools/ci/travis-before-script.sh | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 14e2484110..9094637c80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,7 @@ env: - OPENMC_ENDF_DATA=$HOME/endf-b-vii.1 - OPENMC_MULTIPOLE_LIBRARY=$HOME/multipole_lib - PATH=$PATH:$HOME/NJOY2016/build + - DISPLAY=:99.0 matrix: - OMP=n MPI=n PHDF5=n - OMP=y MPI=n PHDF5=n diff --git a/tools/ci/travis-before-script.sh b/tools/ci/travis-before-script.sh index bbf4980b0f..d0df06f2fd 100755 --- a/tools/ci/travis-before-script.sh +++ b/tools/ci/travis-before-script.sh @@ -1,6 +1,10 @@ #!/bin/bash set -ex +# Allow tests that require GUI as described at: +# https://docs.travis-ci.com/user/gui-and-headless-browsers/#Using-xvfb-to-Run-Tests-That-Require-a-GUI +sh -e /etc/init.d/xvfb start + # Download NNDC HDF5 data if [[ ! -e $HOME/nndc_hdf5/cross_sections.xml ]]; then wget https://anl.box.com/shared/static/a6sw2cep34wlz6b9i9jwiotaqoayxcxt.xz -O - | tar -C $HOME -xvJ From 2027920fdd4e692405c939be5bf0932c54f982d9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Feb 2018 14:52:53 -0600 Subject: [PATCH 071/212] Add unit tests for openmc.RectLattice and openmc.HexLattice --- openmc/lattice.py | 6 +- tests/unit_tests/conftest.py | 12 +- tests/unit_tests/test_data_neutron.py | 1 + tests/unit_tests/test_lattice.py | 344 ++++++++++++++++++++++++++ 4 files changed, 360 insertions(+), 3 deletions(-) create mode 100644 tests/unit_tests/test_lattice.py diff --git a/openmc/lattice.py b/openmc/lattice.py index 933f51af34..730d7dc4a9 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -560,7 +560,11 @@ class RectLattice(Lattice): @property def ndim(self): - return len(self.pitch) + if self.pitch is not None: + return len(self.pitch) + else: + raise ValueError('Number of dimensions cannot be determined until ' + 'the lattice pitch has been set.') @property def shape(self): diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index af534afe35..d618b85def 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -21,10 +21,19 @@ def uo2(): return m +@pytest.fixture(scope='module') +def water(): + m = openmc.Material(name='light water') + m.add_nuclide('H1', 2.0) + m.add_nuclide('O16', 1.0) + m.set_density('g/cm3', 1.0) + m.add_s_alpha_beta('c_H_in_H2O') + return m + + @pytest.fixture(scope='module') def sphere_model(): model = openmc.model.Model() - m = openmc.Material() m.add_nuclide('U235', 1.0) m.set_density('g/cm3', 1.0) @@ -54,7 +63,6 @@ def cell_with_lattice(): lattice = openmc.RectLattice(name='My Lattice') lattice.lower_left = (-4.0, -4.0) lattice.pitch = (4.0, 4.0) - lattice.dimension = (2, 2) lattice.universes = [[univ, univ], [univ, univ]] main_cell = openmc.Cell(fill=lattice) diff --git a/tests/unit_tests/test_data_neutron.py b/tests/unit_tests/test_data_neutron.py index e314d32a42..5713bfbc57 100644 --- a/tests/unit_tests/test_data_neutron.py +++ b/tests/unit_tests/test_data_neutron.py @@ -213,6 +213,7 @@ def test_export_to_hdf5(tmpdir, pu239, gd154): with pytest.raises(NotImplementedError): gd154.export_to_hdf5('gd154.h5') + def test_slbw(xe135): res = xe135.resonances assert isinstance(res, openmc.data.Resonances) diff --git a/tests/unit_tests/test_lattice.py b/tests/unit_tests/test_lattice.py new file mode 100644 index 0000000000..47dc1c029e --- /dev/null +++ b/tests/unit_tests/test_lattice.py @@ -0,0 +1,344 @@ +from math import sqrt +import xml.etree.ElementTree as ET + +import openmc +import pytest + + +@pytest.fixture(scope='module') +def pincell1(uo2, water): + cyl = openmc.ZCylinder(R=0.35) + fuel = openmc.Cell(fill=uo2, region=-cyl) + moderator = openmc.Cell(fill=water, region=+cyl) + + univ = openmc.Universe(cells=[fuel, moderator]) + univ.fuel = fuel + univ.moderator = moderator + return univ + + +@pytest.fixture(scope='module') +def pincell2(uo2, water): + cyl = openmc.ZCylinder(R=0.4) + fuel = openmc.Cell(fill=uo2, region=-cyl) + moderator = openmc.Cell(fill=water, region=+cyl) + + univ = openmc.Universe(cells=[fuel, moderator]) + univ.fuel = fuel + univ.moderator = moderator + return univ + + +@pytest.fixture(scope='module') +def zr(): + zr = openmc.Material() + zr.add_element('Zr', 1.0) + zr.set_density('g/cm3', 1.0) + return zr + + +@pytest.fixture(scope='module') +def rlat2(pincell1, pincell2, uo2, water, zr): + """2D Rectangular lattice for testing.""" + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + n = 3 + u1, u2 = pincell1, pincell2 + lattice = openmc.RectLattice() + lattice.lower_left = (-pitch*n/2, -pitch*n/2) + lattice.pitch = (pitch, pitch) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [u1, u2, u1], + [u2, u1, u2], + [u2, u1, u1] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, all_zr] + lattice.mats = [uo2, water, zr] + lattice.univs = [u1, u2, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def rlat3(pincell1, pincell2, uo2, water, zr): + """3D Rectangular lattice for testing.""" + + # Create another universe for top layer + hydrogen = openmc.Material() + hydrogen.add_element('H', 1.0) + hydrogen.set_density('g/cm3', 0.09) + h_cell = openmc.Cell(fill=hydrogen) + u3 = openmc.Universe(cells=[h_cell]) + + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + n = 3 + u1, u2 = pincell1, pincell2 + lattice = openmc.RectLattice() + lattice.lower_left = (-pitch*n/2, -pitch*n/2, -10.0) + lattice.pitch = (pitch, pitch, 10.0) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [[u1, u2, u1], + [u2, u1, u2], + [u2, u1, u1]], + [[u3, u1, u2], + [u1, u3, u2], + [u2, u1, u1]] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, + h_cell, all_zr] + lattice.mats = [uo2, water, zr, hydrogen] + lattice.univs = [u1, u2, u3, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def hlat2(pincell1, pincell2, uo2, water, zr): + """2D Hexagonal lattice for testing.""" + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + u1, u2 = pincell1, pincell2 + lattice = openmc.HexLattice() + lattice.center = (0., 0.) + lattice.pitch = (pitch,) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [u2, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1], + [u2, u1, u1, u1, u1, u1], + [u2] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, all_zr] + lattice.mats = [uo2, water, zr] + lattice.univs = [u1, u2, lattice.outer] + return lattice + + +@pytest.fixture(scope='module') +def hlat3(pincell1, pincell2, uo2, water, zr): + """3D Hexagonal lattice for testing.""" + + # Create another universe for top layer + hydrogen = openmc.Material() + hydrogen.add_element('H', 1.0) + hydrogen.set_density('g/cm3', 0.09) + h_cell = openmc.Cell(fill=hydrogen) + u3 = openmc.Universe(cells=[h_cell]) + + all_zr = openmc.Cell(fill=zr) + pitch = 1.2 + u1, u2 = pincell1, pincell2 + lattice = openmc.HexLattice() + lattice.center = (0., 0., 0.) + lattice.pitch = (pitch, 10.0) + lattice.outer = openmc.Universe(cells=[all_zr]) + lattice.universes = [ + [[u2, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1, u1], + [u2, u1, u1, u1, u1, u1], + [u2]], + [[u1, u1, u1, u1, u1, u1, u3, u1, u1, u1, u1, u1], + [u1, u1, u1, u3, u1, u1], + [u3]] + ] + + # Add extra attributes for comparison purpose + lattice.cells = [u1.fuel, u1.moderator, u2.fuel, u2.moderator, + h_cell, all_zr] + lattice.mats = [uo2, water, zr, hydrogen] + lattice.univs = [u1, u2, u3, lattice.outer] + return lattice + + +def test_get_nuclides(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, hlat2): + nucs = rlat2.get_nuclides() + assert sorted(nucs) == ['H1', 'O16', 'U235', + 'Zr90', 'Zr91', 'Zr92', 'Zr94', 'Zr96'] + for lat in (rlat3, hlat3): + nucs = rlat3.get_nuclides() + assert sorted(nucs) == ['H1', 'H2', 'O16', 'U235', + 'Zr90', 'Zr91', 'Zr92', 'Zr94', 'Zr96'] + + +def test_get_all_cells(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + cells = set(lat.get_all_cells().values()) + assert not cells ^ set(lat.cells) + + +def test_get_all_materials(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + mats = set(lat.get_all_materials().values()) + assert not mats ^ set(lat.mats) + + +def test_get_all_universes(rlat2, rlat3, hlat2, hlat3): + for lat in (rlat2, rlat3, hlat2, hlat3): + univs = set(lat.get_all_universes().values()) + assert not univs ^ set(lat.univs) + + +def test_get_universe(rlat2, rlat3, hlat2, hlat3): + u1, u2, outer = rlat2.univs + assert rlat2.get_universe((0, 0)) == u2 + assert rlat2.get_universe((1, 0)) == u1 + assert rlat2.get_universe((0, 1)) == u2 + + u1, u2, u3, outer = rlat3.univs + assert rlat3.get_universe((0, 0, 0)) == u2 + assert rlat3.get_universe((2, 2, 0)) == u1 + assert rlat3.get_universe((0, 2, 1)) == u3 + assert rlat3.get_universe((2, 1, 1)) == u2 + + u1, u2, outer = hlat2.univs + assert hlat2.get_universe((0, 0)) == u2 + assert hlat2.get_universe((0, 2)) == u2 + assert hlat2.get_universe((1, 0)) == u1 + assert hlat2.get_universe((-2, 2)) == u1 + + u1, u2, u3, outer = hlat3.univs + assert hlat3.get_universe((0, 0, 0)) == u2 + assert hlat3.get_universe((0, 0, 1)) == u3 + assert hlat3.get_universe((0, 2, 0)) == u2 + assert hlat3.get_universe((0, 2, 1)) == u1 + assert hlat3.get_universe((0, -2, 0)) == u1 + assert hlat3.get_universe((0, -2, 1)) == u3 + + +def test_find(rlat2, rlat3, hlat2, hlat3): + pitch = rlat2.pitch[0] + seq = rlat2.find((0., 0., 0.)) + assert seq[-1] == rlat2.cells[0] + seq = rlat2.find((pitch, 0., 0.)) + assert seq[-1] == rlat2.cells[2] + seq = rlat2.find((0., -pitch, 0.)) + assert seq[-1] == rlat2.cells[0] + seq = rlat2.find((pitch*100, 0., 0.)) + assert seq[-1] == rlat2.cells[-1] + seq = rlat3.find((-pitch, pitch, 5.0)) + assert seq[-1] == rlat3.cells[-2] + + pitch = hlat2.pitch[0] + seq = hlat2.find((0., 0., 0.)) + assert seq[-1] == hlat2.cells[2] + seq = hlat2.find((0.5, 0., 0.)) + assert seq[-1] == hlat2.cells[3] + seq = hlat2.find((sqrt(3)*pitch, 0., 0.)) + assert seq[-1] == hlat2.cells[0] + seq = hlat2.find((0., pitch, 0.)) + assert seq[-1] == hlat2.cells[2] + + # bottom of 3D lattice + seq = hlat3.find((0., 0., -5.)) + assert seq[-1] == hlat3.cells[2] + seq = hlat3.find((0., pitch, -5.)) + assert seq[-1] == hlat3.cells[2] + seq = hlat3.find((0., -pitch, -5.)) + assert seq[-1] == hlat3.cells[0] + seq = hlat3.find((sqrt(3)*pitch, 0., -5.)) + assert seq[-1] == hlat3.cells[0] + + # top of 3D lattice + seq = hlat3.find((0., 0., 5.)) + assert seq[-1] == hlat3.cells[-2] + seq = hlat3.find((0., pitch, 5.)) + assert seq[-1] == hlat3.cells[0] + seq = hlat3.find((0., -pitch, 5.)) + assert seq[-1] == hlat3.cells[-2] + seq = hlat3.find((sqrt(3)*pitch, 0., 5.)) + assert seq[-1] == hlat3.cells[0] + + +def test_clone(rlat2, hlat2, hlat3): + rlat_clone = rlat2.clone() + assert rlat_clone.id != rlat2.id + assert rlat_clone.lower_left == rlat2.lower_left + assert rlat_clone.pitch == rlat2.pitch + + hlat_clone = hlat2.clone() + assert hlat_clone.id != hlat2.id + assert hlat_clone.center == hlat2.center + assert hlat_clone.pitch == hlat2.pitch + + hlat_clone = hlat3.clone() + assert hlat_clone.id != hlat3.id + assert hlat_clone.center == hlat3.center + assert hlat_clone.pitch == hlat3.pitch + + +def test_repr(rlat2, rlat3, hlat2, hlat3): + repr(rlat2) + repr(rlat3) + repr(hlat2) + repr(hlat3) + + +def test_indices_rect(rlat2, rlat3): + # (y, x) indices + assert rlat2.indices == [(0, 0), (0, 1), (0, 2), + (1, 0), (1, 1), (1, 2), + (2, 0), (2, 1), (2, 2)] + # (z, y, x) indices + assert rlat3.indices == [ + (0, 0, 0), (0, 0, 1), (0, 0, 2), + (0, 1, 0), (0, 1, 1), (0, 1, 2), + (0, 2, 0), (0, 2, 1), (0, 2, 2), + (1, 0, 0), (1, 0, 1), (1, 0, 2), + (1, 1, 0), (1, 1, 1), (1, 1, 2), + (1, 2, 0), (1, 2, 1), (1, 2, 2) + ] + + +def test_indices_hex(hlat2, hlat3): + # (r, i) indices + assert hlat2.indices == ( + [(0, i) for i in range(12)] + + [(1, i) for i in range(6)] + + [(2, 0)] + ) + + # (z, r, i) indices + assert hlat3.indices == ( + [(0, 0, i) for i in range(12)] + + [(0, 1, i) for i in range(6)] + + [(0, 2, 0)] + + [(1, 0, i) for i in range(12)] + + [(1, 1, i) for i in range(6)] + + [(1, 2, 0)] + ) + + +def test_xml_rect(rlat2, rlat3): + for lat in (rlat2, rlat3): + geom = ET.Element('geometry') + lat.create_xml_subelement(geom) + elem = geom.find('lattice') + assert elem.tag == 'lattice' + assert elem.get('id') == str(lat.id) + assert len(elem.find('pitch').text.split()) == lat.ndim + assert len(elem.find('lower_left').text.split()) == lat.ndim + assert len(elem.find('universes').text.split()) == len(lat.indices) + + +def test_xml_hex(hlat2, hlat3): + for lat in (hlat2, hlat3): + geom = ET.Element('geometry') + lat.create_xml_subelement(geom) + elem = geom.find('hex_lattice') + assert elem.tag == 'hex_lattice' + assert elem.get('id') == str(lat.id) + assert len(elem.find('center').text.split()) == lat.ndim + assert len(elem.find('pitch').text.split()) == lat.ndim - 1 + assert len(elem.find('universes').text.split()) == len(lat.indices) + + +def test_show_indices(): + for i in range(1, 11): + lines = openmc.HexLattice.show_indices(i).split('\n') + assert len(lines) == 4*i - 3 From 68a01b8fc15e130c842bf7188f94ba946da38bf2 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 06:22:18 -0600 Subject: [PATCH 072/212] Explicitly use int(floor(...)) for Python 2 compatibility --- docs/source/conf.py | 5 +++-- openmc/lattice.py | 12 ++++++------ openmc/mgxs/mgxs.py | 6 +----- openmc/model/triso.py | 12 ++---------- openmc/tallies.py | 2 -- 5 files changed, 12 insertions(+), 25 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 9330315903..b97ff782d9 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -27,8 +27,9 @@ except ImportError: MOCK_MODULES = ['numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial', 'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.interpolate', 'scipy.integrate', 'scipy.optimize', 'scipy.special', - 'scipy.stats', 'h5py', 'pandas', 'uncertainties', 'matplotlib', - 'matplotlib.pyplot','openmoc', 'openmc.data.reconstruct'] + 'scipy.stats', 'scipy.spatial', 'h5py', 'pandas', 'uncertainties', + 'matplotlib', 'matplotlib.pyplot','openmoc', + 'openmc.data.reconstruct'] sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES) import numpy as np diff --git a/openmc/lattice.py b/openmc/lattice.py index 730d7dc4a9..89cfcfe52c 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -607,12 +607,12 @@ class RectLattice(Lattice): element coordinate system """ - ix = floor((point[0] - self.lower_left[0])/self.pitch[0]) - iy = floor((point[1] - self.lower_left[1])/self.pitch[1]) + ix = int(floor((point[0] - self.lower_left[0])/self.pitch[0])) + iy = int(floor((point[1] - self.lower_left[1])/self.pitch[1])) if self.ndim == 2: idx = (ix, iy) else: - iz = floor((point[2] - self.lower_left[2])/self.pitch[2]) + iz = int(floor((point[2] - self.lower_left[2])/self.pitch[2])) idx = (ix, iy, iz) return idx, self.get_local_coordinates(point, idx) @@ -1019,10 +1019,10 @@ class HexLattice(Lattice): iz = 1 else: z = point[2] - self.center[2] - iz = floor(z/self.pitch[1] + 0.5*self.num_axial) + iz = int(floor(z/self.pitch[1] + 0.5*self.num_axial)) alpha = y - x/sqrt(3.) - ix = floor(x/(sqrt(0.75) * self.pitch[0])) - ia = floor(alpha/self.pitch[0]) + ix = int(floor(x/(sqrt(0.75) * self.pitch[0]))) + ia = int(floor(alpha/self.pitch[0])) # Check four lattice elements to see which one is closest based on local # coordinates diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index a557e51cc1..0c0b15ad9d 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -10,6 +10,7 @@ import itertools from six import add_metaclass, string_types import numpy as np +import h5py import openmc import openmc.checkvalue as cv @@ -1682,13 +1683,8 @@ class MGXS(object): ValueError When this method is called before the multi-group cross section is computed from tally data. - ImportError - When h5py is not installed. """ - - import h5py - # Make directory if it does not exist if not os.path.exists(directory): os.makedirs(directory) diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 67bf3bc442..7258a86f21 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -12,11 +12,7 @@ from abc import ABCMeta, abstractproperty, abstractmethod from six import add_metaclass import numpy as np -try: - import scipy.spatial - _SCIPY_AVAILABLE = True -except ImportError: - _SCIPY_AVAILABLE = False +import scipy.spatial import openmc import openmc.checkvalue as cv @@ -742,7 +738,7 @@ def _close_random_pack(domain, particles, contraction_rate): outer_pf = (4/3 * pi * (outer_diameter[0]/2)**3 * n_particles / domain.volume) - j = floor(-log10(outer_pf - inner_pf)) + j = int(floor(-log10(outer_pf - inner_pf))) outer_diameter[0] = (outer_diameter[0] - 0.5**j * contraction_rate * initial_outer_diameter / n_particles) @@ -837,10 +833,6 @@ def _close_random_pack(domain, particles, contraction_rate): if rods: inner_diameter[0] = rods[0][0] - if not _SCIPY_AVAILABLE: - raise ImportError('SciPy must be installed to perform ' - 'close random packing.') - n_particles = len(particles) diameter = 2*domain.particle_radius diff --git a/openmc/tallies.py b/openmc/tallies.py index 235ad2472e..b685dcae39 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1508,8 +1508,6 @@ class Tally(IDManagerMixin): ------ KeyError When this method is called before the Tally is populated with data - ImportError - When Pandas can not be found on the caller's system """ From d45856157626ef8c21957991baafbcec933e5827 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 07:09:51 -0600 Subject: [PATCH 073/212] Upload test coverage results to coveralls --- .travis.yml | 6 ++---- tools/ci/travis-install.sh | 3 +++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9094637c80..8a745c5d69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,17 +30,15 @@ env: - OMP=y MPI=n PHDF5=n - OMP=n MPI=y PHDF5=n - OMP=n MPI=y PHDF5=y - before_install: - sudo add-apt-repository ppa:nschloe/hdf5-backports -y - sudo apt-get update -q - sudo apt-get install libhdf5-serial-dev libhdf5-mpich-dev -y - install: - ./tools/ci/travis-install.sh - before_script: - ./tools/ci/travis-before-script.sh - script: - ./tools/ci/travis-script.sh +after_success: + - coveralls -d tests/.coverage diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index cef34a2e0e..58bcfb789d 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -25,3 +25,6 @@ python tools/ci/travis-install.py # Install Python API in editable mode pip install -e .[test] + +# For uploading to coveralls +pip install python-coveralls From 6044edc24a5dd39e3b71d1a7e67a30762c2619e0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 09:24:41 -0600 Subject: [PATCH 074/212] Add simple test for openmc.Settings --- .gitignore | 2 ++ readme.rst | 6 +++- tests/unit_tests/test_settings.py | 54 +++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tests/unit_tests/test_settings.py diff --git a/.gitignore b/.gitignore index 35f45e747b..8c7cc3e366 100644 --- a/.gitignore +++ b/.gitignore @@ -101,3 +101,5 @@ examples/jupyter/plots .cache/ .tox/ .python-version +.coverage +htmlcov \ No newline at end of file diff --git a/readme.rst b/readme.rst index b7366fe3e1..32cbb34e14 100644 --- a/readme.rst +++ b/readme.rst @@ -2,7 +2,7 @@ OpenMC Monte Carlo Particle Transport Code ========================================== -|licensebadge| |travisbadge| +|licensebadge| |travisbadge| |coverallsbadge| The OpenMC project aims to provide a fully-featured Monte Carlo particle transport code based on modern methods. It is a constructive solid geometry, @@ -74,3 +74,7 @@ OpenMC is distributed under the MIT/X license_. .. |travisbadge| image:: https://travis-ci.org/mit-crpg/openmc.svg?branch=develop :target: https://travis-ci.org/mit-crpg/openmc :alt: Travis CI build status (Linux) + +.. |coverallsbadge| image:: https://coveralls.io/repos/github/mit-crpg/openmc/badge.svg?branch=develop + :target: https://coveralls.io/github/mit-crpg/openmc?branch=develop + :alt: Code Coverage diff --git a/tests/unit_tests/test_settings.py b/tests/unit_tests/test_settings.py new file mode 100644 index 0000000000..f72840be27 --- /dev/null +++ b/tests/unit_tests/test_settings.py @@ -0,0 +1,54 @@ +import openmc +import openmc.stats + + +def test_export_to_xml(run_in_tmpdir): + s = openmc.Settings() + s.run_mode = 'fixed source' + s.batches = 1000 + s.generations_per_batch = 10 + s.inactive = 100 + s.particles = 1000000 + s.keff_trigger = {'type': 'std_dev', 'threshold': 0.001} + s.energy_mode = 'continuous-energy' + s.max_order = 5 + s.source = openmc.Source(space=openmc.stats.Point()) + s.output = {'summary': True, 'tallies': False, 'path': 'here'} + s.verbosity = 7 + s.sourcepoint = {'batches': [50, 150, 500, 1000], 'separate': True, + 'write': True, 'overwrite': True} + s.statepoint = {'batches': [50, 150, 500, 1000]} + s.confidence_intervals = True + s.cross_sections = '/path/to/cross_sections.xml' + s.multipole_library = '/path/to/wmp/' + s.ptables = True + s.run_cmfd = False + s.seed = 17 + s.survival_biasing = True + s.cutoff = {'weight': 0.25, 'weight_avg': 0.5, 'energy': 1.0e-5} + mesh = openmc.Mesh() + mesh.lower_left = (-10., -10., -10.) + mesh.upper_right = (10., 10., 10.) + mesh.dimension = (5, 5, 5) + s.entropy_mesh = mesh + s.trigger_active = True + s.trigger_max_batches = 10000 + s.trigger_batch_interval = 50 + s.no_reduce = False + s.tabular_legendre = {'enable': True, 'num_points': 50} + s.temperature = {'default': 293.6, 'method': 'interpolation', + 'multipole': True, 'range': (200., 1000.)} + s.threads = 8 + s.trace = (10, 1, 20) + s.track = [1, 1, 1, 2, 1, 1] + s.ufs_mesh = mesh + s.resonance_scattering = {'enable': True, 'method': 'ares', + 'energy_min': 1.0, 'energy_max': 1000.0, + 'nuclides': ['U235', 'U238', 'Pu239']} + s.volume_calculations = openmc.VolumeCalculation( + domains=[openmc.Cell()], samples=1000, lower_left=(-10., -10., -10.), + upper_right = (10., 10., 10.)) + s.create_fission_neutrons = True + + # Make sure exporting XML works + s.export_to_xml() From bc4c7d9372c3c4cc33f6606c972423ed0aaddb4f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 09:30:49 -0600 Subject: [PATCH 075/212] Add option in openmc.Settings for log_grid_bins (and remove DD) --- openmc/settings.py | 158 ++++-------------------------- tests/unit_tests/test_settings.py | 1 + 2 files changed, 20 insertions(+), 139 deletions(-) diff --git a/openmc/settings.py b/openmc/settings.py index 9ead82ec61..3c46d0c2c5 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -60,6 +60,8 @@ class Settings(object): type are 'variance', 'std_dev', and 'rel_err'. The threshold value should be a float indicating the variance, standard deviation, or relative error used. + log_grid_bins : int + Number of bins for logarithmic energy grid search max_order : None or int Maximum scattering order to apply globally when in multi-group mode. multipole_library : str @@ -220,19 +222,12 @@ class Settings(object): # Uniform fission source subelement self._ufs_mesh = None - # Domain decomposition subelement - self._dd_mesh_dimension = None - self._dd_mesh_lower_left = None - self._dd_mesh_upper_right = None - self._dd_nodemap = None - self._dd_allow_leakage = False - self._dd_count_interactions = False - self._resonance_scattering = {} self._volume_calculations = cv.CheckedList( VolumeCalculation, 'volume calculations') self._create_fission_neutrons = None + self._log_grid_bins = None @property def run_mode(self): @@ -362,30 +357,6 @@ class Settings(object): def ufs_mesh(self): return self._ufs_mesh - @property - def dd_mesh_dimension(self): - return self._dd_mesh_dimension - - @property - def dd_mesh_lower_left(self): - return self._dd_mesh_lower_left - - @property - def dd_mesh_upper_right(self): - return self._dd_mesh_upper_right - - @property - def dd_nodemap(self): - return self._dd_nodemap - - @property - def dd_allow_leakage(self): - return self._dd_allow_leakage - - @property - def dd_count_interactions(self): - return self._dd_count_interactions - @property def resonance_scattering(self): return self._resonance_scattering @@ -398,6 +369,10 @@ class Settings(object): def create_fission_neutrons(self): return self._create_fission_neutrons + @property + def log_grid_bins(self): + return self._log_grid_bins + @run_mode.setter def run_mode(self, run_mode): cv.check_value('run mode', run_mode, _RUN_MODES) @@ -696,85 +671,6 @@ class Settings(object): cv.check_length('UFS mesh upper-right corner', ufs_mesh.upper_right, 3) self._ufs_mesh = ufs_mesh - @dd_mesh_dimension.setter - def dd_mesh_dimension(self, dimension): - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD mesh dimension', dimension, Iterable, Integral) - cv.check_length('DD mesh dimension', dimension, 3) - - self._dd_mesh_dimension = dimension - - @dd_mesh_lower_left.setter - def dd_mesh_lower_left(self, lower_left): - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD mesh lower left corner', lower_left, Iterable, Real) - cv.check_length('DD mesh lower left corner', lower_left, 3) - - self._dd_mesh_lower_left = lower_left - - @dd_mesh_upper_right.setter - def dd_mesh_upper_right(self, upper_right): - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD mesh upper right corner', upper_right, Iterable, Real) - cv.check_length('DD mesh upper right corner', upper_right, 3) - - self._dd_mesh_upper_right = upper_right - - @dd_nodemap.setter - def dd_nodemap(self, nodemap): - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD nodemap', nodemap, Iterable) - - nodemap = np.array(nodemap).flatten() - - if self._dd_mesh_dimension is None: - msg = 'Must set DD mesh dimension before setting the nodemap' - raise ValueError(msg) - else: - len_nodemap = np.prod(self._dd_mesh_dimension) - - if len(nodemap) < len_nodemap or len(nodemap) > len_nodemap: - msg = 'Unable to set DD nodemap with length "{0}" which ' \ - 'does not have the same dimensionality as the domain ' \ - 'mesh'.format(len(nodemap)) - raise ValueError(msg) - - self._dd_nodemap = nodemap - - @dd_allow_leakage.setter - def dd_allow_leakage(self, allow): - - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD allow leakage', allow, bool) - - self._dd_allow_leakage = allow - - @dd_count_interactions.setter - def dd_count_interactions(self, interactions): - - # TODO: remove this when domain decomposition is merged - warnings.warn('This feature is not yet implemented in a release ' - 'version of openmc') - - cv.check_type('DD count interactions', interactions, bool) - - self._dd_count_interactions = interactions - @resonance_scattering.setter def resonance_scattering(self, res): cv.check_type('resonance scattering settings', res, Mapping) @@ -812,6 +708,12 @@ class Settings(object): create_fission_neutrons, bool) self._create_fission_neutrons = create_fission_neutrons + @log_grid_bins.setter + def log_grid_bins(self, log_grid_bins): + cv.check_type('log grid bins', log_grid_bins, Real) + cv.check_greater_than('log grid bins', log_grid_bins, 0) + self._log_grid_bins = log_grid_bins + def _create_run_mode_subelement(self, root): elem = ET.SubElement(root, "run_mode") elem.text = self._run_mode @@ -1033,33 +935,6 @@ class Settings(object): subelement = ET.SubElement(root, "ufs_mesh") subelement.text = str(self.ufs_mesh.id) - def _create_dd_subelement(self, root): - if self._dd_mesh_lower_left is not None and \ - self._dd_mesh_upper_right is not None and \ - self._dd_mesh_dimension is not None: - - element = ET.SubElement(root, "domain_decomposition") - - subelement = ET.SubElement(element, "mesh") - subsubelement = ET.SubElement(subelement, "dimension") - subsubelement.text = ' '.join(map(str, self._dd_mesh_dimension)) - - subsubelement = ET.SubElement(subelement, "lower_left") - subsubelement.text = ' '.join(map(str, self._dd_mesh_lower_left)) - - subsubelement = ET.SubElement(subelement, "upper_right") - subsubelement.text = ' '.join(map(str, self._dd_mesh_upper_right)) - - if self._dd_nodemap is not None: - subelement = ET.SubElement(element, "nodemap") - subelement.text = ' '.join(map(str, self._dd_nodemap)) - - subelement = ET.SubElement(element, "allow_leakage") - subelement.text = str(self._dd_allow_leakage).lower() - - subelement = ET.SubElement(element, "count_interactions") - subelement.text = str(self._dd_count_interactions).lower() - def _create_resonance_scattering_subelement(self, root): res = self.resonance_scattering if res: @@ -1085,6 +960,11 @@ class Settings(object): elem = ET.SubElement(root, "create_fission_neutrons") elem.text = str(self._create_fission_neutrons).lower() + def _create_log_grid_bins_subelement(self, root): + if self._log_grid_bins is not None: + elem = ET.SubElement(root, "log_grid_bins") + elem.text = str(self._log_grid_bins) + def export_to_xml(self, path='settings.xml'): """Export simulation settings to an XML file. @@ -1128,10 +1008,10 @@ class Settings(object): self._create_trace_subelement(root_element) self._create_track_subelement(root_element) self._create_ufs_mesh_subelement(root_element) - self._create_dd_subelement(root_element) self._create_resonance_scattering_subelement(root_element) self._create_volume_calcs_subelement(root_element) self._create_create_fission_neutrons_subelement(root_element) + self._create_log_grid_bins_subelement(root_element) # Clean the indentation in the file to be user-readable clean_xml_indentation(root_element) diff --git a/tests/unit_tests/test_settings.py b/tests/unit_tests/test_settings.py index f72840be27..e3bfc697eb 100644 --- a/tests/unit_tests/test_settings.py +++ b/tests/unit_tests/test_settings.py @@ -49,6 +49,7 @@ def test_export_to_xml(run_in_tmpdir): domains=[openmc.Cell()], samples=1000, lower_left=(-10., -10., -10.), upper_right = (10., 10., 10.)) s.create_fission_neutrons = True + s.log_grid_bins = 2000 # Make sure exporting XML works s.export_to_xml() From c710184fba7b2eb1aa8063f082013b04dc7cd6f7 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 09:46:16 -0600 Subject: [PATCH 076/212] Run tests from root directory --- .travis.yml | 2 +- tools/ci/travis-script.sh | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8a745c5d69..05e239025e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -41,4 +41,4 @@ before_script: script: - ./tools/ci/travis-script.sh after_success: - - coveralls -d tests/.coverage + - coveralls diff --git a/tools/ci/travis-script.sh b/tools/ci/travis-script.sh index 468cd0cc8a..ee445b517f 100755 --- a/tools/ci/travis-script.sh +++ b/tools/ci/travis-script.sh @@ -2,14 +2,13 @@ set -ex # Run source check -cd tests if [[ $TRAVIS_PYTHON_VERSION == "3.4" && $OMP == 'n' && $MPI == 'n' ]]; then - ./check_source.py + pushd tests && python check_source.py && popd fi # Run regression and unit tests if [[ $MPI == 'y' ]]; then - pytest --cov=../openmc -v --mpi + pytest --cov=openmc -v --mpi tests else - pytest --cov=../openmc -v + pytest --cov=openmc -v tests fi From 36244692fd0e4d40b0d55a7cb90f6e6e68514e22 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 5 Feb 2018 08:09:47 -0600 Subject: [PATCH 077/212] Use mpicc and mpicxx for MPI configurations --- docs/source/usersguide/install.rst | 13 +++++++------ tools/ci/travis-install.py | 4 +++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 48188928cf..638d425014 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -263,14 +263,15 @@ should be used: Compiling with MPI ++++++++++++++++++ -To compile with MPI, set the :envvar:`FC` and :envvar:`CC` environment variables -to the path to the MPI Fortran and C wrappers, respectively. For example, in a -bash shell: +To compile with MPI, set the :envvar:`FC`, :envvar:`CC`, and :envvar:`CXX` +environment variables to the path to the MPI Fortran, C, and C++ wrappers, +respectively. For example, in a bash shell: .. code-block:: sh - export FC=mpif90 + export FC=mpifort export CC=mpicc + export CXX=mpicxx cmake /path/to/openmc Note that in many shells, environment variables can be set for a single command, @@ -278,7 +279,7 @@ i.e. .. code-block:: sh - FC=mpif90 CC=mpicc cmake /path/to/openmc + FC=mpifort CC=mpicc CXX=mpicxx cmake /path/to/openmc Selecting HDF5 Installation +++++++++++++++++++++++++++ @@ -354,7 +355,7 @@ follows: .. code-block:: sh mkdir build && cd build - FC=ifort CC=icc FFLAGS=-mmic cmake -Dopenmp=on .. + FC=ifort CC=icc CXX=icpc FFLAGS=-mmic cmake -Dopenmp=on .. make Note that unless an HDF5 build for the Intel Xeon Phi (Knights Corner) is diff --git a/tools/ci/travis-install.py b/tools/ci/travis-install.py index bd7f886dbc..15e4d576b7 100644 --- a/tools/ci/travis-install.py +++ b/tools/ci/travis-install.py @@ -33,9 +33,11 @@ def install(omp=False, mpi=False, phdf5=False): if not omp: cmake_cmd.append('-Dopenmp=off') - # For MPI, we just need to change the Fortran compiler + # Use MPI wrappers when building in parallel if mpi: os.environ['FC'] = 'mpifort' if which('mpifort') else 'mpif90' + os.environ['CC'] = 'mpicc' + os.environ['CXX'] = 'mpicxx' # Tell CMake to prefer parallel HDF5 if specified if phdf5: From c428cee667fcc7341c3cb3eca5798b03d50d13f4 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 24 Dec 2017 16:06:05 +0700 Subject: [PATCH 078/212] Remove __future__ and six imports --- openmc/arithmetic.py | 22 +++++----- openmc/cell.py | 3 +- openmc/cmfd.py | 4 +- openmc/data/ace.py | 4 +- openmc/data/angle_energy.py | 5 +-- openmc/data/decay.py | 5 +-- openmc/data/endf.py | 5 +-- openmc/data/energy_distribution.py | 4 +- openmc/data/function.py | 4 +- openmc/data/library.py | 3 +- openmc/data/multipole.py | 3 +- openmc/data/neutron.py | 6 +-- openmc/data/njoy.py | 1 - openmc/data/product.py | 3 +- openmc/data/reaction.py | 4 +- openmc/element.py | 4 +- openmc/executor.py | 5 +-- openmc/filter.py | 5 +-- openmc/geometry.py | 4 +- openmc/lattice.py | 8 +--- openmc/macroscopic.py | 4 +- openmc/material.py | 23 +++++------ openmc/mesh.py | 5 +-- openmc/mgxs/library.py | 23 +++++------ openmc/mgxs/mdgxs.py | 49 ++++++++++------------ openmc/mgxs/mgxs.py | 65 ++++++++++++++---------------- openmc/mgxs_library.py | 5 +-- openmc/model/funcs.py | 1 - openmc/model/triso.py | 5 +-- openmc/nuclide.py | 2 - openmc/plots.py | 21 +++++----- openmc/plotter.py | 7 ++-- openmc/region.py | 4 +- openmc/settings.py | 9 ++--- openmc/source.py | 4 +- openmc/stats/multivariate.py | 7 +--- openmc/stats/univariate.py | 4 +- openmc/surface.py | 12 ++---- openmc/tallies.py | 22 +++++----- openmc/tally_derivative.py | 8 +--- openmc/trigger.py | 4 +- openmc/universe.py | 6 +-- scripts/openmc-ace-to-hdf5 | 2 +- scripts/openmc-convert-mcnp70-data | 3 +- scripts/openmc-convert-mcnp71-data | 3 +- scripts/openmc-get-jeff-data | 7 +--- scripts/openmc-get-multipole-data | 7 +--- scripts/openmc-get-nndc-data | 5 +-- scripts/openmc-plot-mesh-tally | 12 +++--- scripts/openmc-track-to-vtk | 2 +- scripts/openmc-update-inputs | 4 +- scripts/openmc-update-mgxs | 3 +- scripts/openmc-validate-xml | 4 +- scripts/openmc-voxel-to-silovtk | 3 +- setup.py | 6 +-- 55 files changed, 171 insertions(+), 282 deletions(-) diff --git a/openmc/arithmetic.py b/openmc/arithmetic.py index fe002f1e31..4a5e7486a8 100644 --- a/openmc/arithmetic.py +++ b/openmc/arithmetic.py @@ -2,7 +2,6 @@ import sys import copy from collections import Iterable -from six import string_types import numpy as np import pandas as pd @@ -86,18 +85,18 @@ class CrossScore(object): @left_score.setter def left_score(self, left_score): cv.check_type('left_score', left_score, - string_types + (CrossScore, AggregateScore)) + (str, CrossScore, AggregateScore)) self._left_score = left_score @right_score.setter def right_score(self, right_score): cv.check_type('right_score', right_score, - string_types + (CrossScore, AggregateScore)) + (str, CrossScore, AggregateScore)) self._right_score = right_score @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -202,7 +201,7 @@ class CrossNuclide(object): @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -335,7 +334,7 @@ class CrossFilter(object): @binary_op.setter def binary_op(self, binary_op): - cv.check_type('binary_op', binary_op, string_types) + cv.check_type('binary_op', binary_op, str) cv.check_value('binary_op', binary_op, _TALLY_ARITHMETIC_OPS) self._binary_op = binary_op @@ -482,12 +481,12 @@ class AggregateScore(object): @scores.setter def scores(self, scores): - cv.check_iterable_type('scores', scores, string_types) + cv.check_iterable_type('scores', scores, str) self._scores = scores @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types +(CrossScore,)) + cv.check_type('aggregate_op', aggregate_op, (str, CrossScore)) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -561,13 +560,12 @@ class AggregateNuclide(object): @nuclides.setter def nuclides(self, nuclides): - cv.check_iterable_type('nuclides', nuclides, - string_types + (openmc.Nuclide, CrossNuclide)) + cv.check_iterable_type('nuclides', nuclides, (str, CrossNuclide)) self._nuclides = nuclides @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types) + cv.check_type('aggregate_op', aggregate_op, str) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op @@ -690,7 +688,7 @@ class AggregateFilter(object): @aggregate_op.setter def aggregate_op(self, aggregate_op): - cv.check_type('aggregate_op', aggregate_op, string_types) + cv.check_type('aggregate_op', aggregate_op, str) cv.check_value('aggregate_op', aggregate_op, _TALLY_AGGREGATE_OPS) self._aggregate_op = aggregate_op diff --git a/openmc/cell.py b/openmc/cell.py index 074fadc06d..087f2816d4 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -6,7 +6,6 @@ from xml.etree import ElementTree as ET import sys import warnings -from six import string_types import numpy as np import openmc @@ -203,7 +202,7 @@ class Cell(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('cell name', name, string_types) + cv.check_type('cell name', name, str) self._name = name else: self._name = '' diff --git a/openmc/cmfd.py b/openmc/cmfd.py index c3df3f1047..236491923d 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -15,8 +15,6 @@ from numbers import Real, Integral from xml.etree import ElementTree as ET import sys -from six import string_types - from openmc.clean_xml import clean_xml_indentation from openmc.checkvalue import (check_type, check_length, check_value, check_greater_than, check_less_than) @@ -338,7 +336,7 @@ class CMFD(object): @display.setter def display(self, display): - check_type('CMFD display', display, string_types) + check_type('CMFD display', display, str) check_value('CMFD display', display, ['balance', 'dominance', 'entropy', 'source']) self._display = display diff --git a/openmc/data/ace.py b/openmc/data/ace.py index 9827df5b9d..385408bd48 100644 --- a/openmc/data/ace.py +++ b/openmc/data/ace.py @@ -15,12 +15,10 @@ generates ACE-format cross sections. """ -from __future__ import division, unicode_literals from os import SEEK_CUR import struct import sys -from six import string_types import numpy as np from openmc.mixin import EqualityMixin @@ -153,7 +151,7 @@ class Library(EqualityMixin): """ def __init__(self, filename, table_names=None, verbose=False): - if isinstance(table_names, string_types): + if isinstance(table_names, str): table_names = [table_names] if table_names is not None: table_names = set(table_names) diff --git a/openmc/data/angle_energy.py b/openmc/data/angle_energy.py index 8bf95152a9..d67cc6b266 100644 --- a/openmc/data/angle_energy.py +++ b/openmc/data/angle_energy.py @@ -1,14 +1,11 @@ from abc import ABCMeta, abstractmethod from io import StringIO -from six import add_metaclass - import openmc.data from openmc.mixin import EqualityMixin -@add_metaclass(ABCMeta) -class AngleEnergy(EqualityMixin): +class AngleEnergy(EqualityMixin, metaclass=ABCMeta): """Distribution in angle and energy of a secondary particle.""" @abstractmethod def to_hdf5(self, group): diff --git a/openmc/data/decay.py b/openmc/data/decay.py index 4327b2fc35..3d365b6c70 100644 --- a/openmc/data/decay.py +++ b/openmc/data/decay.py @@ -5,7 +5,6 @@ from numbers import Real import re from warnings import warn -from six import string_types import numpy as np try: from uncertainties import ufloat, unumpy, UFloat @@ -278,12 +277,12 @@ class DecayMode(EqualityMixin): @modes.setter def modes(self, modes): - cv.check_type('decay modes', modes, Iterable, string_types) + cv.check_type('decay modes', modes, Iterable, str) self._modes = modes @parent.setter def parent(self, parent): - cv.check_type('parent nuclide', parent, string_types) + cv.check_type('parent nuclide', parent, str) self._parent = parent diff --git a/openmc/data/endf.py b/openmc/data/endf.py index 0fa75ded89..882874b590 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -6,15 +6,12 @@ Data File ENDF-6". The latest version from June 2009 can be found at http://www-nds.iaea.org/ndspub/documents/endf/endf102/endf102.pdf """ -from __future__ import print_function, division, unicode_literals - import io import re import os from math import pi from collections import OrderedDict, Iterable -from six import string_types import numpy as np from numpy.polynomial.polynomial import Polynomial @@ -301,7 +298,7 @@ class Evaluation(object): """ def __init__(self, filename_or_obj): - if isinstance(filename_or_obj, string_types): + if isinstance(filename_or_obj, str): fh = open(filename_or_obj, 'r') else: fh = filename_or_obj diff --git a/openmc/data/energy_distribution.py b/openmc/data/energy_distribution.py index c3740beaf0..e8c92801cf 100644 --- a/openmc/data/energy_distribution.py +++ b/openmc/data/energy_distribution.py @@ -3,7 +3,6 @@ from collections import Iterable from numbers import Integral, Real from warnings import warn -from six import add_metaclass import numpy as np from .function import Tabulated1D, INTERPOLATION_SCHEME @@ -14,8 +13,7 @@ from .data import EV_PER_MEV from .endf import get_tab1_record, get_tab2_record -@add_metaclass(ABCMeta) -class EnergyDistribution(EqualityMixin): +class EnergyDistribution(EqualityMixin, metaclass=ABCMeta): """Abstract superclass for all energy distributions.""" def __init__(self): pass diff --git a/openmc/data/function.py b/openmc/data/function.py index 0515a57c0c..2d3a8ce9c1 100644 --- a/openmc/data/function.py +++ b/openmc/data/function.py @@ -2,7 +2,6 @@ from abc import ABCMeta, abstractmethod from collections import Iterable, Callable from numbers import Real, Integral -from six import add_metaclass import numpy as np import openmc.data @@ -14,8 +13,7 @@ INTERPOLATION_SCHEME = {1: 'histogram', 2: 'linear-linear', 3: 'linear-log', 4: 'log-linear', 5: 'log-log'} -@add_metaclass(ABCMeta) -class Function1D(EqualityMixin): +class Function1D(EqualityMixin, metaclass=ABCMeta): """A function of one independent variable with HDF5 support.""" @abstractmethod def __call__(self): pass diff --git a/openmc/data/library.py b/openmc/data/library.py index c179f78f8c..34cd380a55 100644 --- a/openmc/data/library.py +++ b/openmc/data/library.py @@ -1,6 +1,5 @@ import os import xml.etree.ElementTree as ET -from six import string_types import h5py @@ -125,7 +124,7 @@ class DataLibrary(EqualityMixin): raise ValueError("Either path or OPENMC_CROSS_SECTIONS " "environmental variable must be set") - check_type('path', path, string_types) + check_type('path', path, str) tree = ET.parse(path) root = tree.getroot() diff --git a/openmc/data/multipole.py b/openmc/data/multipole.py index 4e77e16ea9..33078f5046 100644 --- a/openmc/data/multipole.py +++ b/openmc/data/multipole.py @@ -3,7 +3,6 @@ from math import exp, erf, pi, sqrt import h5py import numpy as np -from six import string_types from . import WMP_VERSION from .data import K_BOLTZMANN @@ -300,7 +299,7 @@ class WindowedMultipole(EqualityMixin): @formalism.setter def formalism(self, formalism): if formalism is not None: - cv.check_type('formalism', formalism, string_types) + cv.check_type('formalism', formalism, str) cv.check_value('formalism', formalism, ('MLBW', 'RM')) self._formalism = formalism diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index 7dcac5d6e6..8d59316892 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -1,4 +1,3 @@ -from __future__ import division, unicode_literals import sys from collections import OrderedDict, Iterable, Mapping, MutableMapping from io import StringIO @@ -10,7 +9,6 @@ import shutil import tempfile from warnings import warn -from six import string_types import numpy as np import h5py @@ -245,7 +243,7 @@ class IncidentNeutron(EqualityMixin): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @property @@ -301,7 +299,7 @@ class IncidentNeutron(EqualityMixin): def urr(self, urr): cv.check_type('probability table dictionary', urr, MutableMapping) for key, value in urr: - cv.check_type('probability table temperature', key, string_types) + cv.check_type('probability table temperature', key, str) cv.check_type('probability tables', value, ProbabilityTables) self._urr = urr diff --git a/openmc/data/njoy.py b/openmc/data/njoy.py index b08b3bdfb3..be16d96f81 100644 --- a/openmc/data/njoy.py +++ b/openmc/data/njoy.py @@ -1,4 +1,3 @@ -from __future__ import print_function import argparse from collections import namedtuple from io import StringIO diff --git a/openmc/data/product.py b/openmc/data/product.py index bcffec0daf..b7d89ba0ea 100644 --- a/openmc/data/product.py +++ b/openmc/data/product.py @@ -3,7 +3,6 @@ from io import StringIO from numbers import Real import sys -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -113,7 +112,7 @@ class Product(EqualityMixin): @particle.setter def particle(self, particle): - cv.check_type('product particle type', particle, string_types) + cv.check_type('product particle type', particle, str) self._particle = particle @yield_.setter diff --git a/openmc/data/reaction.py b/openmc/data/reaction.py index ac3a049ab1..737885f357 100644 --- a/openmc/data/reaction.py +++ b/openmc/data/reaction.py @@ -1,11 +1,9 @@ -from __future__ import division, unicode_literals from collections import Iterable, Callable, MutableMapping from copy import deepcopy from numbers import Real, Integral from warnings import warn from io import StringIO -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -863,7 +861,7 @@ class Reaction(EqualityMixin): def xs(self, xs): cv.check_type('reaction cross section dictionary', xs, MutableMapping) for key, value in xs.items(): - cv.check_type('reaction cross section temperature', key, string_types) + cv.check_type('reaction cross section temperature', key, str) cv.check_type('reaction cross section', value, Callable) self._xs = xs diff --git a/openmc/element.py b/openmc/element.py index 5ba19c63c4..25cb97538c 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -1,8 +1,6 @@ from collections import OrderedDict import re import os - -from six import string_types from xml.etree import ElementTree as ET import openmc @@ -29,7 +27,7 @@ class Element(str): """ def __new__(cls, name): - cv.check_type('element name', name, string_types) + cv.check_type('element name', name, str) cv.check_length('element name', name, 1, 2) return super(Element, cls).__new__(cls, name) diff --git a/openmc/executor.py b/openmc/executor.py index ada662a12f..e3768f4c61 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -1,10 +1,7 @@ -from __future__ import print_function from collections import Iterable import subprocess from numbers import Integral -from six import string_types - import openmc from openmc import VolumeCalculation @@ -203,7 +200,7 @@ def run(particles=None, threads=None, geometry_debug=False, if geometry_debug: args.append('-g') - if isinstance(restart_file, string_types): + if isinstance(restart_file, str): args += ['-r', restart_file] if tracks: diff --git a/openmc/filter.py b/openmc/filter.py index 21bb64f8d5..8f57a80906 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -1,4 +1,3 @@ -from __future__ import division from abc import ABCMeta from collections import Iterable, OrderedDict import copy @@ -8,7 +7,6 @@ from numbers import Real, Integral import operator from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import pandas as pd @@ -70,8 +68,7 @@ class FilterMeta(ABCMeta): **kwargs) -@add_metaclass(FilterMeta) -class Filter(IDManagerMixin): +class Filter(IDManagerMixin, metaclass=FilterMeta): """Tally modifier that describes phase-space and other characteristics. Parameters diff --git a/openmc/geometry.py b/openmc/geometry.py index ac068e2b04..7e14272698 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -2,8 +2,6 @@ from collections import OrderedDict, Iterable from copy import deepcopy from xml.etree import ElementTree as ET -from six import string_types - import openmc from openmc.clean_xml import clean_xml_indentation from openmc.checkvalue import check_type @@ -139,7 +137,7 @@ class Geometry(object): """ # Make sure we are working with an iterable return_list = (isinstance(paths, Iterable) and - not isinstance(paths, string_types)) + not isinstance(paths, str)) path_list = paths if return_list else [paths] indices = [] diff --git a/openmc/lattice.py b/openmc/lattice.py index 89cfcfe52c..1bb82f6284 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -1,5 +1,3 @@ -from __future__ import division - from abc import ABCMeta from collections import OrderedDict, Iterable from copy import deepcopy @@ -7,7 +5,6 @@ from math import sqrt, floor from numbers import Real, Integral from xml.etree import ElementTree as ET -from six import add_metaclass, string_types import numpy as np import openmc.checkvalue as cv @@ -15,8 +12,7 @@ import openmc from openmc.mixin import IDManagerMixin -@add_metaclass(ABCMeta) -class Lattice(IDManagerMixin): +class Lattice(IDManagerMixin, metaclass=ABCMeta): """A repeating structure wherein each element is a universe. Parameters @@ -73,7 +69,7 @@ class Lattice(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('lattice name', name, string_types) + cv.check_type('lattice name', name, str) self._name = name else: self._name = '' diff --git a/openmc/macroscopic.py b/openmc/macroscopic.py index cdb5cbb395..f5bd90f3a4 100644 --- a/openmc/macroscopic.py +++ b/openmc/macroscopic.py @@ -1,5 +1,3 @@ -from six import string_types - from openmc.checkvalue import check_type @@ -19,7 +17,7 @@ class Macroscopic(str): """ def __new__(cls, name): - check_type('name', name, string_types) + check_type('name', name, str) return super(Macroscopic, cls).__new__(cls, name) @property diff --git a/openmc/material.py b/openmc/material.py index a59fdaa285..cb3024447b 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -4,7 +4,6 @@ from numbers import Real, Integral import warnings from xml.etree import ElementTree as ET -from six import string_types import numpy as np import openmc @@ -217,7 +216,7 @@ class Material(IDManagerMixin): def name(self, name): if name is not None: cv.check_type('name for Material ID="{}"'.format(self._id), - name, string_types) + name, str) self._name = name else: self._name = '' @@ -243,7 +242,7 @@ class Material(IDManagerMixin): @isotropic.setter def isotropic(self, isotropic): cv.check_iterable_type('Isotropic scattering nuclides', isotropic, - string_types) + str) self._isotropic = list(isotropic) @classmethod @@ -345,7 +344,7 @@ class Material(IDManagerMixin): warnings.warn('This feature is not yet implemented in a release ' 'version of openmc') - if not isinstance(filename, string_types) and filename is not None: + if not isinstance(filename, str) and filename is not None: msg = 'Unable to add OTF material file to Material ID="{}" with a ' \ 'non-string name "{}"'.format(self._id, filename) raise ValueError(msg) @@ -379,7 +378,7 @@ class Material(IDManagerMixin): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(nuclide, string_types): + if not isinstance(nuclide, str): msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ 'non-string value "{}"'.format(self._id, nuclide) raise ValueError(msg) @@ -405,7 +404,7 @@ class Material(IDManagerMixin): Nuclide to remove """ - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('nuclide', nuclide, str) # If the Material contains the Nuclide, delete it for nuc in self._nuclides: @@ -434,7 +433,7 @@ class Material(IDManagerMixin): 'has already been added'.format(self._id, macroscopic) raise ValueError(msg) - if not isinstance(macroscopic, string_types): + if not isinstance(macroscopic, str): msg = 'Unable to add a Macroscopic to Material ID="{}" with a ' \ 'non-string value "{}"'.format(self._id, macroscopic) raise ValueError(msg) @@ -465,7 +464,7 @@ class Material(IDManagerMixin): """ - if not isinstance(macroscopic, string_types): + if not isinstance(macroscopic, str): msg = 'Unable to remove a Macroscopic "{}" in Material ID="{}" ' \ 'since it is not a string'.format(self._id, macroscopic) raise ValueError(msg) @@ -498,7 +497,7 @@ class Material(IDManagerMixin): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(element, string_types): + if not isinstance(element, str): msg = 'Unable to add an Element to Material ID="{}" with a ' \ 'non-string value "{}"'.format(self._id, element) raise ValueError(msg) @@ -563,7 +562,7 @@ class Material(IDManagerMixin): 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(name, string_types): + if not isinstance(name, str): msg = 'Unable to add an S(a,b) table to Material ID="{}" with a ' \ 'non-string table name "{}"'.format(self._id, name) raise ValueError(msg) @@ -903,12 +902,12 @@ class Materials(cv.CheckedList): @cross_sections.setter def cross_sections(self, cross_sections): - cv.check_type('cross sections', cross_sections, string_types) + cv.check_type('cross sections', cross_sections, str) self._cross_sections = cross_sections @multipole_library.setter def multipole_library(self, multipole_library): - cv.check_type('cross sections', multipole_library, string_types) + cv.check_type('cross sections', multipole_library, str) self._multipole_library = multipole_library def add_material(self, material): diff --git a/openmc/mesh.py b/openmc/mesh.py index b315b2628b..d937e25ce9 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -3,7 +3,6 @@ from numbers import Real, Integral from xml.etree import ElementTree as ET import sys -from six import string_types import numpy as np import openmc.checkvalue as cv @@ -87,7 +86,7 @@ class Mesh(IDManagerMixin): def name(self, name): if name is not None: cv.check_type('name for mesh ID="{0}"'.format(self._id), - name, string_types) + name, str) self._name = name else: self._name = '' @@ -95,7 +94,7 @@ class Mesh(IDManagerMixin): @type.setter def type(self, meshtype): cv.check_type('type for mesh ID="{0}"'.format(self._id), - meshtype, string_types) + meshtype, str) cv.check_value('type for mesh ID="{0}"'.format(self._id), meshtype, ['regular']) self._type = meshtype diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index b83305783f..c8b151e024 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -6,7 +6,6 @@ from numbers import Integral from collections import OrderedDict, Iterable from warnings import warn -from six import string_types import numpy as np import openmc @@ -271,7 +270,7 @@ class Library(object): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @mgxs_types.setter @@ -280,7 +279,7 @@ class Library(object): if mgxs_types == 'all': self._mgxs_types = all_mgxs_types else: - cv.check_iterable_type('mgxs_types', mgxs_types, string_types) + cv.check_iterable_type('mgxs_types', mgxs_types, str) for mgxs_type in mgxs_types: cv.check_value('mgxs_type', mgxs_type, all_mgxs_types) self._mgxs_types = mgxs_types @@ -814,8 +813,8 @@ class Library(object): 'since a statepoint has not yet been loaded' raise ValueError(msg) - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) import h5py @@ -857,8 +856,8 @@ class Library(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) # Make directory if it does not exist if not os.path.exists(directory): @@ -892,8 +891,8 @@ class Library(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) # Make directory if it does not exist if not os.path.exists(directory): @@ -953,8 +952,8 @@ class Library(object): cv.check_type('domain', domain, (openmc.Material, openmc.Cell, openmc.Universe, openmc.Mesh)) - cv.check_type('xsdata_name', xsdata_name, string_types) - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('xsdata_name', xsdata_name, str) + cv.check_type('nuclide', nuclide, str) cv.check_value('xs_type', xs_type, ['macro', 'micro']) if subdomain is not None: cv.check_iterable_type('subdomain', subdomain, Integral, @@ -1213,7 +1212,7 @@ class Library(object): cv.check_value('xs_type', xs_type, ['macro', 'micro']) if xsdata_names is not None: - cv.check_iterable_type('xsdata_names', xsdata_names, string_types) + cv.check_iterable_type('xsdata_names', xsdata_names, str) # If gathering material-specific data, set the xs_type to macro if not self.by_nuclide: diff --git a/openmc/mgxs/mdgxs.py b/openmc/mgxs/mdgxs.py index d3f1a0646b..7799183ff7 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -1,5 +1,3 @@ -from __future__ import division - from collections import Iterable, OrderedDict import itertools from numbers import Integral @@ -9,7 +7,6 @@ import sys import copy from abc import ABCMeta -from six import add_metaclass, string_types import numpy as np import openmc @@ -29,7 +26,6 @@ MDGXS_TYPES = ['delayed-nu-fission', MAX_DELAYED_GROUPS = 8 -@add_metaclass(ABCMeta) class MDGXS(MGXS): """An abstract multi-delayed-group cross section for some energy and delayed group structures within some spatial domain. @@ -355,7 +351,7 @@ class MDGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -363,7 +359,7 @@ class MDGXS(MGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyFilter) @@ -371,7 +367,7 @@ class MDGXS(MGXS): (self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -475,7 +471,7 @@ class MDGXS(MGXS): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_iterable_type('energy_groups', groups, Integral) cv.check_type('delayed groups', delayed_groups, list, int) @@ -585,7 +581,7 @@ class MDGXS(MGXS): return # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -602,7 +598,7 @@ class MDGXS(MGXS): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -725,8 +721,8 @@ class MDGXS(MGXS): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -816,11 +812,11 @@ class MDGXS(MGXS): """ - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, string_types) - if not isinstance(delayed_groups, string_types): + cv.check_iterable_type('nuclides', nuclides, str) + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -858,7 +854,7 @@ class MDGXS(MGXS): columns = self._df_convert_columns_to_bins(df) # Select out those groups the user requested - if not isinstance(groups, string_types): + if not isinstance(groups, str): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1288,7 +1284,7 @@ class ChiDelayed(MDGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -1296,7 +1292,7 @@ class ChiDelayed(MDGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) for group in groups: filters.append(openmc.EnergyoutFilter) @@ -1304,7 +1300,7 @@ class ChiDelayed(MDGXS): (self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -1352,7 +1348,7 @@ class ChiDelayed(MDGXS): # Get chi delayed for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) @@ -1914,7 +1910,6 @@ class DecayRate(MDGXS): return self._get_homogenized_mgxs(other_mgxs, 'delayed-nu-fission') -@add_metaclass(ABCMeta) class MatrixMDGXS(MDGXS): """An abstract multi-delayed-group cross section for some energy group and delayed group structure within some spatial domain. This class is @@ -2117,7 +2112,7 @@ class MatrixMDGXS(MDGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) for subdomain in subdomains: @@ -2125,7 +2120,7 @@ class MatrixMDGXS(MDGXS): filter_bins.append((subdomain,)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) for group in in_groups: filters.append(openmc.EnergyFilter) @@ -2133,7 +2128,7 @@ class MatrixMDGXS(MDGXS): self.energy_groups.get_group_bounds(group),)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -2141,7 +2136,7 @@ class MatrixMDGXS(MDGXS): self.energy_groups.get_group_bounds(group),)) # Construct list of delayed group tuples for all requested groups - if not isinstance(delayed_groups, string_types): + if not isinstance(delayed_groups, str): cv.check_type('delayed groups', delayed_groups, list, int) for delayed_group in delayed_groups: filters.append(openmc.DelayedGroupFilter) @@ -2312,7 +2307,7 @@ class MatrixMDGXS(MDGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -2329,7 +2324,7 @@ class MatrixMDGXS(MDGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 0c0b15ad9d..949f0fba00 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -1,5 +1,3 @@ -from __future__ import division - from collections import OrderedDict from numbers import Integral import warnings @@ -8,7 +6,6 @@ import copy from abc import ABCMeta import itertools -from six import add_metaclass, string_types import numpy as np import h5py @@ -116,8 +113,7 @@ def _df_column_convert_to_bin(df, current_name, new_name, values_to_bin, df.rename(columns={current_name: new_name}, inplace=True) -@add_metaclass(ABCMeta) -class MGXS(object): +class MGXS(metaclass=ABCMeta): """An abstract multi-group cross section for some energy group structure within some spatial domain. @@ -580,7 +576,7 @@ class MGXS(object): @name.setter def name(self, name): - cv.check_type('name', name, string_types) + cv.check_type('name', name, str) self._name = name @by_nuclide.setter @@ -590,7 +586,7 @@ class MGXS(object): @nuclides.setter def nuclides(self, nuclides): - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) self._nuclides = nuclides @estimator.setter @@ -806,7 +802,7 @@ class MGXS(object): """ - cv.check_type('nuclide', nuclide, string_types) + cv.check_type('nuclide', nuclide, str) # Get list of all nuclides in the spatial domain nuclides = self.domain.get_nuclide_densities() @@ -1033,7 +1029,7 @@ class MGXS(object): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) @@ -1044,7 +1040,7 @@ class MGXS(object): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) filters.append(openmc.EnergyFilter) energy_bins = [] @@ -1219,7 +1215,7 @@ class MGXS(object): """ # Construct a collection of the subdomain filter bins to average across - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) subdomains = [(subdomain,) for subdomain in subdomains] subdomains = [tuple(subdomains)] @@ -1376,7 +1372,7 @@ class MGXS(object): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_iterable_type('energy_groups', groups, Integral) # Build lists of filters and filter bins to slice @@ -1530,7 +1526,7 @@ class MGXS(object): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1547,7 +1543,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -1698,7 +1694,7 @@ class MGXS(object): xs_results = h5py.File(filename, 'w', libver=libver) # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -1719,7 +1715,7 @@ class MGXS(object): elif nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -1797,8 +1793,8 @@ class MGXS(object): """ - cv.check_type('filename', filename, string_types) - cv.check_type('directory', directory, string_types) + cv.check_type('filename', filename, str) + cv.check_type('directory', directory, str) cv.check_value('format', format, ['csv', 'excel', 'pickle', 'latex']) cv.check_value('xs_type', xs_type, ['macro', 'micro']) @@ -1884,10 +1880,10 @@ class MGXS(object): """ - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) if nuclides != 'all' and nuclides != 'sum': - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) cv.check_value('xs_type', xs_type, ['macro', 'micro']) # Get a Pandas DataFrame from the derived xs tally @@ -1923,7 +1919,7 @@ class MGXS(object): columns = self._df_convert_columns_to_bins(df) # Select out those groups the user requested - if not isinstance(groups, string_types): + if not isinstance(groups, str): if 'group in' in df: df = df[df['group in'].isin(groups)] if 'group out' in df: @@ -1976,7 +1972,6 @@ class MGXS(object): return 'cm^-1' if xs_type == 'macro' else 'barns' -@add_metaclass(ABCMeta) class MatrixMGXS(MGXS): """An abstract multi-group cross section for some energy group structure within some spatial domain. This class is specifically intended for @@ -2164,7 +2159,7 @@ class MatrixMGXS(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) @@ -2174,7 +2169,7 @@ class MatrixMGXS(MGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) filters.append(openmc.EnergyFilter) for group in in_groups: @@ -2182,7 +2177,7 @@ class MatrixMGXS(MGXS): filter_bins.append(tuple(energy_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -2342,7 +2337,7 @@ class MatrixMGXS(MGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -2359,7 +2354,7 @@ class MatrixMGXS(MGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -4307,7 +4302,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) subdomain_bins = [] @@ -4316,7 +4311,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(in_groups, string_types): + if not isinstance(in_groups, str): cv.check_iterable_type('groups', in_groups, Integral) filters.append(openmc.EnergyFilter) energy_bins = [] @@ -4326,7 +4321,7 @@ class ScatterMatrixXS(MatrixMGXS): filter_bins.append(tuple(energy_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(out_groups, string_types): + if not isinstance(out_groups, str): cv.check_iterable_type('groups', out_groups, Integral) for group in out_groups: filters.append(openmc.EnergyoutFilter) @@ -4539,7 +4534,7 @@ class ScatterMatrixXS(MatrixMGXS): """ # Construct a collection of the subdomains to report - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral) elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) @@ -4556,7 +4551,7 @@ class ScatterMatrixXS(MatrixMGXS): if nuclides == 'sum': nuclides = ['sum'] else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) else: nuclides = ['sum'] @@ -5582,7 +5577,7 @@ class Chi(MGXS): filter_bins = [] # Construct a collection of the domain filter bins - if not isinstance(subdomains, string_types): + if not isinstance(subdomains, str): cv.check_iterable_type('subdomains', subdomains, Integral, max_depth=3) filters.append(_DOMAIN_TO_FILTER[self.domain_type]) @@ -5592,7 +5587,7 @@ class Chi(MGXS): filter_bins.append(tuple(subdomain_bins)) # Construct list of energy group bounds tuples for all requested groups - if not isinstance(groups, string_types): + if not isinstance(groups, str): cv.check_iterable_type('groups', groups, Integral) filters.append(openmc.EnergyoutFilter) energy_bins = [] @@ -5640,7 +5635,7 @@ class Chi(MGXS): # Get chi for user-specified nuclides in the domain else: - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) xs = self.xs_tally.get_values(filters=filters, filter_bins=filter_bins, nuclides=nuclides, value=value) diff --git a/openmc/mgxs_library.py b/openmc/mgxs_library.py index ebfae2fb0d..e315f33140 100644 --- a/openmc/mgxs_library.py +++ b/openmc/mgxs_library.py @@ -2,7 +2,6 @@ import copy from numbers import Real, Integral import os -from six import string_types import numpy as np import h5py from scipy.interpolate import interp1d @@ -381,7 +380,7 @@ class XSdata(object): @name.setter def name(self, name): - check_type('name for XSdata', name, string_types) + check_type('name for XSdata', name, str) self._name = name @energy_groups.setter @@ -2517,7 +2516,7 @@ class MGXSLibrary(object): """ - check_type('filename', filename, string_types) + check_type('filename', filename, str) # Create and write to the HDF5 file file = h5py.File(filename, "w", libver=libver) diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index 589765d2c8..b5afdf08d1 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -1,4 +1,3 @@ -from __future__ import division from collections import Iterable, OrderedDict from math import sqrt from numbers import Real diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 7258a86f21..0fe138bd70 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -1,4 +1,3 @@ -from __future__ import division import copy import warnings import itertools @@ -10,7 +9,6 @@ from heapq import heappush, heappop from math import pi, sin, cos, floor, log10, sqrt from abc import ABCMeta, abstractproperty, abstractmethod -from six import add_metaclass import numpy as np import scipy.spatial @@ -92,8 +90,7 @@ class TRISO(openmc.Cell): k_min:k_max+1, j_min:j_max+1, i_min:i_max+1])) -@add_metaclass(ABCMeta) -class _Domain(object): +class _Domain(metaclass=ABCMeta): """Container in which to pack particles. Parameters diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 2e5a8e1193..73247e1aa2 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -1,7 +1,5 @@ import warnings -from six import string_types - import openmc.checkvalue as cv diff --git a/openmc/plots.py b/openmc/plots.py index a60b2a3094..bfff2d7e90 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -4,7 +4,6 @@ from xml.etree import ElementTree as ET import sys import warnings -from six import string_types import numpy as np import openmc @@ -297,7 +296,7 @@ class Plot(IDManagerMixin): @name.setter def name(self, name): - cv.check_type('plot name', name, string_types) + cv.check_type('plot name', name, str) self._name = name @width.setter @@ -322,7 +321,7 @@ class Plot(IDManagerMixin): @filename.setter def filename(self, filename): - cv.check_type('filename', filename, string_types) + cv.check_type('filename', filename, str) self._filename = filename @color_by.setter @@ -343,7 +342,7 @@ class Plot(IDManagerMixin): @background.setter def background(self, background): cv.check_type('plot background', background, Iterable) - if isinstance(background, string_types): + if isinstance(background, str): if background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(background)) else: @@ -359,7 +358,7 @@ class Plot(IDManagerMixin): for key, value in colors.items(): cv.check_type('plot color key', key, (openmc.Cell, openmc.Material)) cv.check_type('plot color value', value, Iterable) - if isinstance(value, string_types): + if isinstance(value, str): if value.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(value)) else: @@ -380,7 +379,7 @@ class Plot(IDManagerMixin): @mask_background.setter def mask_background(self, mask_background): cv.check_type('plot mask background', mask_background, Iterable) - if isinstance(mask_background, string_types): + if isinstance(mask_background, str): if mask_background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(mask_background)) else: @@ -558,7 +557,7 @@ class Plot(IDManagerMixin): cv.check_type('background', background, Iterable) # Get a background (R,G,B) tuple to apply in alpha compositing - if isinstance(background, string_types): + if isinstance(background, str): if background.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color.".format(background)) background = _SVG_COLORS[background.lower()] @@ -570,7 +569,7 @@ class Plot(IDManagerMixin): # other than those the user wishes to highlight for domain, color in self.colors.items(): if domain not in domains: - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] r, g, b = color r = int(((1-alpha) * background[0]) + (alpha * r)) @@ -610,7 +609,7 @@ class Plot(IDManagerMixin): if self._background is not None: subelement = ET.SubElement(element, "background") color = self._background - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.text = ' '.join(str(x) for x in color) @@ -619,7 +618,7 @@ class Plot(IDManagerMixin): key=lambda x: x[0].id): subelement = ET.SubElement(element, "color") subelement.set("id", str(domain.id)) - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.set("rgb", ' '.join(str(x) for x in color)) @@ -629,7 +628,7 @@ class Plot(IDManagerMixin): str(d.id) for d in self._mask_components)) color = self._mask_background if color is not None: - if isinstance(color, string_types): + if isinstance(color, str): color = _SVG_COLORS[color.lower()] subelement.set("background", ' '.join( str(x) for x in color)) diff --git a/openmc/plotter.py b/openmc/plotter.py index 810ee5d27c..1bf6fe46fd 100644 --- a/openmc/plotter.py +++ b/openmc/plotter.py @@ -2,7 +2,6 @@ from numbers import Integral, Real from itertools import chain import string -from six import string_types import matplotlib.pyplot as plt import numpy as np @@ -137,7 +136,7 @@ def plot_xs(this, types, divisor_types=None, temperature=294., data_type=None, data_type = 'material' elif isinstance(this, openmc.Macroscopic): data_type = 'macroscopic' - elif isinstance(this, string_types): + elif isinstance(this, str): if this[-1] in string.digits: data_type = 'nuclide' else: @@ -275,7 +274,7 @@ def calculate_cexs(this, data_type, types, temperature=294., sab_name=None, # Check types cv.check_type('temperature', temperature, Real) if sab_name: - cv.check_type('sab_name', sab_name, string_types) + cv.check_type('sab_name', sab_name, str) if enrichment: cv.check_type('enrichment', enrichment, Real) @@ -648,7 +647,7 @@ def calculate_mgxs(this, data_type, types, orders=None, temperature=294., cv.check_type('temperature', temperature, Real) if enrichment: cv.check_type('enrichment', enrichment, Real) - cv.check_iterable_type('types', types, string_types) + cv.check_iterable_type('types', types, str) cv.check_type("cross_sections", cross_sections, str) library = openmc.MGXSLibrary.from_hdf5(cross_sections) diff --git a/openmc/region.py b/openmc/region.py index 54797f5688..c9bd3b5fc0 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -2,14 +2,12 @@ from abc import ABCMeta, abstractmethod from collections import Iterable, OrderedDict, MutableSequence from copy import deepcopy -from six import add_metaclass import numpy as np from openmc.checkvalue import check_type -@add_metaclass(ABCMeta) -class Region(object): +class Region(metaclass=ABCMeta): """Region of space that can be assigned to a cell. Region is an abstract base class that is inherited by diff --git a/openmc/settings.py b/openmc/settings.py index 3c46d0c2c5..1bbc7a4ec3 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -4,7 +4,6 @@ import warnings from xml.etree import ElementTree as ET import sys -from six import string_types import numpy as np from openmc.clean_xml import clean_xml_indentation @@ -459,7 +458,7 @@ class Settings(object): if key in ('summary', 'tallies'): cv.check_type("output['{}']".format(key), value, bool) else: - cv.check_type("output['path']", value, string_types) + cv.check_type("output['path']", value, str) self._output = output @verbosity.setter @@ -511,7 +510,7 @@ class Settings(object): warnings.warn('Settings.cross_sections has been deprecated and will be ' 'removed in a future version. Materials.cross_sections ' 'should defined instead.', DeprecationWarning) - cv.check_type('cross sections', cross_sections, string_types) + cv.check_type('cross sections', cross_sections, str) self._cross_sections = cross_sections @multipole_library.setter @@ -520,7 +519,7 @@ class Settings(object): 'be removed in a future version. ' 'Materials.multipole_library should defined instead.', DeprecationWarning) - cv.check_type('multipole library', multipole_library, string_types) + cv.check_type('multipole library', multipole_library, str) self._multipole_library = multipole_library @ptables.setter @@ -692,7 +691,7 @@ class Settings(object): cv.check_greater_than(name, value, 0) elif key == 'nuclides': cv.check_type('resonance scattering nuclides', value, - Iterable, string_types) + Iterable, str) self._resonance_scattering = res @volume_calculations.setter diff --git a/openmc/source.py b/openmc/source.py index 1aee435147..932062278c 100644 --- a/openmc/source.py +++ b/openmc/source.py @@ -2,8 +2,6 @@ from numbers import Real import sys from xml.etree import ElementTree as ET -from six import string_types - from openmc.stats.univariate import Univariate from openmc.stats.multivariate import UnitSphere, Spatial import openmc.checkvalue as cv @@ -78,7 +76,7 @@ class Source(object): @file.setter def file(self, filename): - cv.check_type('source file', filename, string_types) + cv.check_type('source file', filename, str) self._file = filename @space.setter diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index 0ab11b7c54..ba2debaeaf 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -5,15 +5,13 @@ from numbers import Real import sys from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import openmc.checkvalue as cv from openmc.stats.univariate import Univariate, Uniform -@add_metaclass(ABCMeta) -class UnitSphere(object): +class UnitSphere(metaclass=ABCMeta): """Distribution of points on the unit sphere. This abstract class is used for angular distributions, since a direction is @@ -181,8 +179,7 @@ class Monodirectional(UnitSphere): return element -@add_metaclass(ABCMeta) -class Spatial(object): +class Spatial(metaclass=ABCMeta): """Distribution of locations in three-dimensional Euclidean space. Classes derived from this abstract class can be used for spatial diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index 38683e6927..47a281d213 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -4,7 +4,6 @@ from numbers import Real import sys from xml.etree import ElementTree as ET -from six import add_metaclass import numpy as np import openmc.checkvalue as cv @@ -15,8 +14,7 @@ _INTERPOLATION_SCHEMES = ['histogram', 'linear-linear', 'linear-log', 'log-linear', 'log-log'] -@add_metaclass(ABCMeta) -class Univariate(EqualityMixin): +class Univariate(EqualityMixin, metaclass=ABCMeta): """Probability distribution of a single random variable. The Univariate class is an abstract class that can be derived to implement a diff --git a/openmc/surface.py b/openmc/surface.py index eb44a4fe8d..694e9fd221 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -1,4 +1,3 @@ -from __future__ import division from abc import ABCMeta from collections import OrderedDict from copy import deepcopy @@ -6,7 +5,6 @@ from functools import partial from numbers import Real, Integral from xml.etree import ElementTree as ET -from six import add_metaclass, string_types import numpy as np from openmc.checkvalue import check_type, check_value @@ -115,14 +113,14 @@ class Surface(IDManagerMixin): @name.setter def name(self, name): if name is not None: - check_type('surface name', name, string_types) + check_type('surface name', name, str) self._name = name else: self._name = '' @boundary_type.setter def boundary_type(self, boundary_type): - check_type('boundary type', boundary_type, string_types) + check_type('boundary type', boundary_type, str) check_value('boundary type', boundary_type, _BOUNDARY_TYPES) self._boundary_type = boundary_type @@ -738,8 +736,7 @@ class ZPlane(Plane): return point[2] - self.z0 -@add_metaclass(ABCMeta) -class Cylinder(Surface): +class Cylinder(Surface, metaclass=ABCMeta): """A cylinder whose length is parallel to the x-, y-, or z-axis. Parameters @@ -1305,8 +1302,7 @@ class Sphere(Surface): return x**2 + y**2 + z**2 - self.r**2 -@add_metaclass(ABCMeta) -class Cone(Surface): +class Cone(Surface, metaclass=ABCMeta): """A conical surface parallel to the x-, y-, or z-axis. Parameters diff --git a/openmc/tallies.py b/openmc/tallies.py index b685dcae39..17c298a8db 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1,5 +1,3 @@ -from __future__ import division - from collections import Iterable, MutableSequence import copy import re @@ -10,7 +8,6 @@ import operator import warnings from xml.etree import ElementTree as ET -from six import string_types import numpy as np import pandas as pd import scipy.sparse as sps @@ -31,9 +28,8 @@ _PRODUCT_TYPES = ['tensor', 'entrywise'] # The following indicate acceptable types when setting Tally.scores, # Tally.nuclides, and Tally.filters -_SCORE_CLASSES = string_types + (openmc.CrossScore, openmc.AggregateScore) -_NUCLIDE_CLASSES = string_types + (openmc.Nuclide, openmc.CrossNuclide, - openmc.AggregateNuclide) +_SCORE_CLASSES = (str, openmc.CrossScore, openmc.AggregateScore) +_NUCLIDE_CLASSES = (str, openmc.CrossNuclide, openmc.AggregateNuclide) _FILTER_CLASSES = (openmc.Filter, openmc.CrossFilter, openmc.AggregateFilter) # Valid types of estimators @@ -359,7 +355,7 @@ class Tally(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('tally name', name, string_types) + cv.check_type('tally name', name, str) self._name = name else: self._name = '' @@ -412,7 +408,7 @@ class Tally(IDManagerMixin): raise ValueError(msg) # If score is a string, strip whitespace - if isinstance(score, string_types): + if isinstance(score, str): scores[i] = score.strip() self._scores = cv.CheckedList(_SCORE_CLASSES, 'tally scores', scores) @@ -1327,7 +1323,7 @@ class Tally(IDManagerMixin): """ - cv.check_iterable_type('nuclides', nuclides, string_types) + cv.check_iterable_type('nuclides', nuclides, str) # Determine the score indices from any of the requested scores if nuclides: @@ -1362,7 +1358,7 @@ class Tally(IDManagerMixin): """ for score in scores: - if not isinstance(score, string_types + (openmc.CrossScore,)): + if not isinstance(score, (str, openmc.CrossScore)): msg = 'Unable to get score indices for score "{0}" in Tally ' \ 'ID="{1}" since it is not a string or CrossScore'\ .format(score, self.id) @@ -1555,7 +1551,7 @@ class Tally(IDManagerMixin): column_name = 'score' for score in self.scores: - if isinstance(score, string_types + (openmc.CrossScore,)): + if isinstance(score, (str, openmc.CrossScore)): scores.append(str(score)) elif isinstance(score, openmc.AggregateScore): scores.append(score.name) @@ -2192,11 +2188,11 @@ class Tally(IDManagerMixin): raise ValueError(msg) # Check that the scores are valid - if not isinstance(score1, string_types + (openmc.CrossScore,)): + if not isinstance(score1, (str, openmc.CrossScore)): msg = 'Unable to swap score1 "{0}" in Tally ID="{1}" since it is ' \ 'not a string or CrossScore'.format(score1, self.id) raise ValueError(msg) - elif not isinstance(score2, string_types + (openmc.CrossScore,)): + elif not isinstance(score2, (str, openmc.CrossScore)): msg = 'Unable to swap score2 "{0}" in Tally ID="{1}" since it is ' \ 'not a string or CrossScore'.format(score2, self.id) raise ValueError(msg) diff --git a/openmc/tally_derivative.py b/openmc/tally_derivative.py index facc56f447..9be748b2cb 100644 --- a/openmc/tally_derivative.py +++ b/openmc/tally_derivative.py @@ -1,11 +1,7 @@ -from __future__ import division - import sys from numbers import Integral from xml.etree import ElementTree as ET -from six import string_types - import openmc.checkvalue as cv from openmc.mixin import EqualityMixin, IDManagerMixin @@ -81,7 +77,7 @@ class TallyDerivative(EqualityMixin, IDManagerMixin): @variable.setter def variable(self, var): if var is not None: - cv.check_type('derivative variable', var, string_types) + cv.check_type('derivative variable', var, str) cv.check_value('derivative variable', var, ('density', 'nuclide_density', 'temperature')) self._variable = var @@ -95,7 +91,7 @@ class TallyDerivative(EqualityMixin, IDManagerMixin): @nuclide.setter def nuclide(self, nuc): if nuc is not None: - cv.check_type('derivative nuclide', nuc, string_types) + cv.check_type('derivative nuclide', nuc, str) self._nuclide = nuc def to_xml_element(self): diff --git a/openmc/trigger.py b/openmc/trigger.py index 69ec8c6200..a5ac1d1e83 100644 --- a/openmc/trigger.py +++ b/openmc/trigger.py @@ -4,8 +4,6 @@ import sys import warnings from collections import Iterable -from six import string_types - import openmc.checkvalue as cv @@ -76,7 +74,7 @@ class Trigger(object): @scores.setter def scores(self, scores): - cv.check_type('trigger scores', scores, Iterable, string_types) + cv.check_type('trigger scores', scores, Iterable, str) # Set scores making sure not to have duplicates self._scores = [] diff --git a/openmc/universe.py b/openmc/universe.py index 4a0a1a9aac..55f574c536 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -1,11 +1,9 @@ -from __future__ import division from collections import OrderedDict, Iterable from copy import copy, deepcopy from numbers import Integral, Real import random import sys -from six import string_types import matplotlib.pyplot as plt import numpy as np @@ -97,7 +95,7 @@ class Universe(IDManagerMixin): @name.setter def name(self, name): if name is not None: - cv.check_type('universe name', name, string_types) + cv.check_type('universe name', name, str) self._name = name else: self._name = '' @@ -237,7 +235,7 @@ class Universe(IDManagerMixin): # Convert to RGBA if necessary colors = copy(colors) for obj, color in colors.items(): - if isinstance(color, string_types): + if isinstance(color, str): if color.lower() not in _SVG_COLORS: raise ValueError("'{}' is not a valid color." .format(color)) diff --git a/scripts/openmc-ace-to-hdf5 b/scripts/openmc-ace-to-hdf5 index 3235a2da63..29c987e07c 100755 --- a/scripts/openmc-ace-to-hdf5 +++ b/scripts/openmc-ace-to-hdf5 @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 import argparse import os diff --git a/scripts/openmc-convert-mcnp70-data b/scripts/openmc-convert-mcnp70-data index 0489b25de4..75b3b0a5a8 100755 --- a/scripts/openmc-convert-mcnp70-data +++ b/scripts/openmc-convert-mcnp70-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import argparse from collections import defaultdict import glob diff --git a/scripts/openmc-convert-mcnp71-data b/scripts/openmc-convert-mcnp71-data index 061f8f46f0..ce8c427d60 100755 --- a/scripts/openmc-convert-mcnp71-data +++ b/scripts/openmc-convert-mcnp71-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import argparse from collections import defaultdict import glob diff --git a/scripts/openmc-get-jeff-data b/scripts/openmc-get-jeff-data index 6d9e086a91..9f426a4930 100755 --- a/scripts/openmc-get-jeff-data +++ b/scripts/openmc-get-jeff-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import os from collections import defaultdict import sys @@ -9,9 +8,7 @@ import zipfile import glob import argparse from string import digits - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen import openmc.data diff --git a/scripts/openmc-get-multipole-data b/scripts/openmc-get-multipole-data index bf0add2840..ea25396488 100755 --- a/scripts/openmc-get-multipole-data +++ b/scripts/openmc-get-multipole-data @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import print_function import os import shutil import subprocess @@ -9,9 +8,7 @@ import tarfile import glob import hashlib import argparse - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen description = """ diff --git a/scripts/openmc-get-nndc-data b/scripts/openmc-get-nndc-data index e2c1e7ce3a..a04eed6cd6 100755 --- a/scripts/openmc-get-nndc-data +++ b/scripts/openmc-get-nndc-data @@ -1,6 +1,5 @@ #!/usr/bin/env python -from __future__ import print_function import os import shutil import subprocess @@ -9,9 +8,7 @@ import tarfile import glob import hashlib import argparse - -from six.moves import input -from six.moves.urllib.request import urlopen +from urllib.request import urlopen import openmc.data diff --git a/scripts/openmc-plot-mesh-tally b/scripts/openmc-plot-mesh-tally index c273a6d592..0dfb29b9b3 100755 --- a/scripts/openmc-plot-mesh-tally +++ b/scripts/openmc-plot-mesh-tally @@ -1,16 +1,16 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Python script to plot tally data generated by OpenMC.""" import os import sys import argparse +import tkinter as tk +import tkinter.filedialog as filedialog +import tkinter.font as font +import tkinter.messagebox as messagebox +import tkinter.ttk as ttk -import six.moves.tkinter as tk -import six.moves.tkinter_filedialog as filedialog -import six.moves.tkinter_font as font -import six.moves.tkinter_messagebox as messagebox -import six.moves.tkinter_ttk as ttk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.backends.backend_tkagg import NavigationToolbar2TkAgg from matplotlib.figure import Figure diff --git a/scripts/openmc-track-to-vtk b/scripts/openmc-track-to-vtk index 1dd632f9dd..fa154a2a7f 100755 --- a/scripts/openmc-track-to-vtk +++ b/scripts/openmc-track-to-vtk @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Convert HDF5 particle track to VTK poly data. diff --git a/scripts/openmc-update-inputs b/scripts/openmc-update-inputs index 3eb850207e..ef7cdf47bb 100755 --- a/scripts/openmc-update-inputs +++ b/scripts/openmc-update-inputs @@ -1,10 +1,8 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Update OpenMC's input XML files to the latest format. """ -from __future__ import print_function - import argparse from difflib import get_close_matches from itertools import chain diff --git a/scripts/openmc-update-mgxs b/scripts/openmc-update-mgxs index f33adfc005..8559affb95 100755 --- a/scripts/openmc-update-mgxs +++ b/scripts/openmc-update-mgxs @@ -1,10 +1,9 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """Update OpenMC's deprecated multi-group cross section XML files to the latest HDF5-based format. """ -from __future__ import print_function import os import warnings import xml.etree.ElementTree as ET diff --git a/scripts/openmc-validate-xml b/scripts/openmc-validate-xml index e5a45f4691..f36ba2b5d3 100755 --- a/scripts/openmc-validate-xml +++ b/scripts/openmc-validate-xml @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from __future__ import print_function +#!/usr/bin/env python3 import os import sys diff --git a/scripts/openmc-voxel-to-silovtk b/scripts/openmc-voxel-to-silovtk index 9748cc3bba..e0cfc0a5ba 100755 --- a/scripts/openmc-voxel-to-silovtk +++ b/scripts/openmc-voxel-to-silovtk @@ -1,6 +1,5 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -from __future__ import division, print_function import struct import sys from argparse import ArgumentParser diff --git a/setup.py b/setup.py index 7bffc516f0..2a42dd65dd 100755 --- a/setup.py +++ b/setup.py @@ -48,11 +48,7 @@ kwargs = { 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Topic :: Scientific/Engineering' - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', @@ -60,7 +56,7 @@ kwargs = { # Required dependencies 'install_requires': [ - 'six', 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', + 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', 'pandas', 'lxml', 'uncertainties' ], From 1ccf6c3e5e3656cc6a1425425f8dbb30b89eec8e Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 24 Dec 2017 16:18:22 +0700 Subject: [PATCH 079/212] Use tempfile.TemporaryDirectory() --- openmc/data/neutron.py | 9 +-------- openmc/data/njoy.py | 7 +------ openmc/data/thermal.py | 8 +------- 3 files changed, 3 insertions(+), 21 deletions(-) diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index 8d59316892..4f02af1a48 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -840,10 +840,7 @@ class IncidentNeutron(EqualityMixin): Incident neutron continuous-energy data """ - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Run NJOY to create an ACE library ace_file = os.path.join(tmpdir, 'ace') xsdir_file = os.path.join(tmpdir, 'xsdir') @@ -871,8 +868,4 @@ class IncidentNeutron(EqualityMixin): data.energy['0K'] = xs.x data[2].xs['0K'] = xs - finally: - # Get rid of temporary files - shutil.rmtree(tmpdir) - return data diff --git a/openmc/data/njoy.py b/openmc/data/njoy.py index be16d96f81..b2894b3d1c 100644 --- a/openmc/data/njoy.py +++ b/openmc/data/njoy.py @@ -149,10 +149,7 @@ def run(commands, tapein, tapeout, input_filename=None, stdout=False, with open(input_filename, 'w') as f: f.write(commands) - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Copy evaluations to appropriates 'tapes' for tape_num, filename in tapein.items(): tmpfilename = os.path.join(tmpdir, 'tape{}'.format(tape_num)) @@ -186,8 +183,6 @@ def run(commands, tapein, tapeout, input_filename=None, stdout=False, tmpfilename = os.path.join(tmpdir, 'tape{}'.format(tape_num)) if os.path.isfile(tmpfilename): shutil.move(tmpfilename, filename) - finally: - shutil.rmtree(tmpdir) def make_pendf(filename, pendf='pendf', error=0.001, stdout=False): diff --git a/openmc/data/thermal.py b/openmc/data/thermal.py index 68192de039..4f89d8e834 100644 --- a/openmc/data/thermal.py +++ b/openmc/data/thermal.py @@ -623,10 +623,7 @@ class ThermalScattering(EqualityMixin): Thermal scattering data """ - # Create temporary directory -- it would be preferable to use - # TemporaryDirectory(), but it is only available in Python 3.2 - tmpdir = tempfile.mkdtemp() - try: + with tempfile.TemporaryDirectory() as tmpdir: # Run NJOY to create an ACE library ace_file = os.path.join(tmpdir, 'ace') xsdir_file = os.path.join(tmpdir, 'xsdir') @@ -638,8 +635,5 @@ class ThermalScattering(EqualityMixin): data = cls.from_ace(lib.tables[0]) for table in lib.tables[1:]: data.add_temperature_from_ace(table) - finally: - # Get rid of temporary files - shutil.rmtree(tmpdir) return data From deab4b3d337ee91b4411089562e6b8824a25ce90 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 24 Dec 2017 16:34:25 +0700 Subject: [PATCH 080/212] Use empty-argument form of super() --- .travis.yml | 3 +- openmc/capi/cell.py | 2 +- openmc/capi/filter.py | 6 +- openmc/capi/nuclide.py | 2 +- openmc/capi/tally.py | 2 +- openmc/checkvalue.py | 6 +- openmc/data/angle_distribution.py | 2 +- openmc/data/correlated.py | 2 +- openmc/data/energy_distribution.py | 18 +++--- openmc/data/kalbach_mann.py | 2 +- openmc/data/laboratory.py | 2 +- openmc/data/resonance.py | 18 +++--- openmc/element.py | 2 +- openmc/filter.py | 9 ++- openmc/lattice.py | 4 +- openmc/macroscopic.py | 2 +- openmc/material.py | 6 +- openmc/mgxs/mdgxs.py | 49 ++++++--------- openmc/mgxs/mgxs.py | 96 +++++++++++++----------------- openmc/model/triso.py | 8 +-- openmc/nuclide.py | 2 +- openmc/plots.py | 6 +- openmc/stats/multivariate.py | 12 ++-- openmc/stats/univariate.py | 12 ++-- openmc/surface.py | 30 +++++----- openmc/tallies.py | 8 +-- 26 files changed, 142 insertions(+), 169 deletions(-) diff --git a/.travis.yml b/.travis.yml index 05e239025e..de83325e03 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,9 @@ sudo: required dist: trusty language: python python: - - "2.7" - "3.4" + - "3.5" + - "3.6" addons: apt: packages: diff --git a/openmc/capi/cell.py b/openmc/capi/cell.py index 0c4b72c749..0cadfd6af4 100644 --- a/openmc/capi/cell.py +++ b/openmc/capi/cell.py @@ -81,7 +81,7 @@ class Cell(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Cell, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index 1b52af6db9..74c6828d60 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -87,7 +87,7 @@ class Filter(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Filter, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid @@ -110,7 +110,7 @@ class EnergyFilter(Filter): filter_type = 'energy' def __init__(self, bins=None, uid=None, new=True, index=None): - super(EnergyFilter, self).__init__(uid, new, index) + super().__init__(uid, new, index) if bins is not None: self.bins = bins @@ -167,7 +167,7 @@ class MaterialFilter(Filter): filter_type = 'material' def __init__(self, bins=None, uid=None, new=True, index=None): - super(MaterialFilter, self).__init__(uid, new, index) + super().__init__(uid, new, index) if bins is not None: self.bins = bins diff --git a/openmc/capi/nuclide.py b/openmc/capi/nuclide.py index e07872e583..54d131498f 100644 --- a/openmc/capi/nuclide.py +++ b/openmc/capi/nuclide.py @@ -58,7 +58,7 @@ class Nuclide(_FortranObject): def __new__(cls, *args): if args not in cls.__instances: - instance = super(Nuclide, cls).__new__(cls) + instance = super().__new__(cls) cls.__instances[args] = instance return cls.__instances[args] diff --git a/openmc/capi/tally.py b/openmc/capi/tally.py index 751f0e6031..aaf709e612 100644 --- a/openmc/capi/tally.py +++ b/openmc/capi/tally.py @@ -172,7 +172,7 @@ class Tally(_FortranObjectWithID): index = mapping[uid]._index if index not in cls.__instances: - instance = super(Tally, cls).__new__(cls) + instance = super().__new__(cls) instance._index = index if uid is not None: instance.id = uid diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index aa4dc067f9..643ea4820f 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -288,7 +288,7 @@ class CheckedList(list): """ def __init__(self, expected_type, name, items=[]): - super(CheckedList, self).__init__() + super().__init__() self.expected_type = expected_type self.name = name for item in items: @@ -319,7 +319,7 @@ class CheckedList(list): """ check_type(self.name, item, self.expected_type) - super(CheckedList, self).append(item) + super().append(item) def insert(self, index, item): """Insert item before index @@ -333,4 +333,4 @@ class CheckedList(list): """ check_type(self.name, item, self.expected_type) - super(CheckedList, self).insert(index, item) + super().insert(index, item) diff --git a/openmc/data/angle_distribution.py b/openmc/data/angle_distribution.py index ad3ba89193..71e3d2f309 100644 --- a/openmc/data/angle_distribution.py +++ b/openmc/data/angle_distribution.py @@ -34,7 +34,7 @@ class AngleDistribution(EqualityMixin): """ def __init__(self, energy, mu): - super(AngleDistribution, self).__init__() + super().__init__() self.energy = energy self.mu = mu diff --git a/openmc/data/correlated.py b/openmc/data/correlated.py index 49d116efd0..ba69e6aa6c 100644 --- a/openmc/data/correlated.py +++ b/openmc/data/correlated.py @@ -45,7 +45,7 @@ class CorrelatedAngleEnergy(AngleEnergy): """ def __init__(self, breakpoints, interpolation, energy, energy_out, mu): - super(CorrelatedAngleEnergy, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/energy_distribution.py b/openmc/data/energy_distribution.py index e8c92801cf..55588bd648 100644 --- a/openmc/data/energy_distribution.py +++ b/openmc/data/energy_distribution.py @@ -114,7 +114,7 @@ class ArbitraryTabulated(EnergyDistribution): """ def __init__(self, energy, pdf): - super(ArbitraryTabulated, self).__init__() + super().__init__() self.energy = energy self.pdf = pdf @@ -182,7 +182,7 @@ class GeneralEvaporation(EnergyDistribution): """ def __init__(self, theta, g, u): - super(GeneralEvaporation, self).__init__() + super().__init__() self.theta = theta self.g = g self.u = u @@ -245,7 +245,7 @@ class MaxwellEnergy(EnergyDistribution): """ def __init__(self, theta, u): - super(MaxwellEnergy, self).__init__() + super().__init__() self.theta = theta self.u = u @@ -378,7 +378,7 @@ class Evaporation(EnergyDistribution): """ def __init__(self, theta, u): - super(Evaporation, self).__init__() + super().__init__() self.theta = theta self.u = u @@ -514,7 +514,7 @@ class WattEnergy(EnergyDistribution): """ def __init__(self, a, b, u): - super(WattEnergy, self).__init__() + super().__init__() self.a = a self.b = b self.u = u @@ -682,7 +682,7 @@ class MadlandNix(EnergyDistribution): """ def __init__(self, efl, efh, tm): - super(MadlandNix, self).__init__() + super().__init__() self.efl = efl self.efh = efh self.tm = tm @@ -805,7 +805,7 @@ class DiscretePhoton(EnergyDistribution): """ def __init__(self, primary_flag, energy, atomic_weight_ratio): - super(DiscretePhoton, self).__init__() + super().__init__() self.primary_flag = primary_flag self.energy = energy self.atomic_weight_ratio = atomic_weight_ratio @@ -914,7 +914,7 @@ class LevelInelastic(EnergyDistribution): """ def __init__(self, threshold, mass_ratio): - super(LevelInelastic, self).__init__() + super().__init__() self.threshold = threshold self.mass_ratio = mass_ratio @@ -1019,7 +1019,7 @@ class ContinuousTabular(EnergyDistribution): """ def __init__(self, breakpoints, interpolation, energy, energy_out): - super(ContinuousTabular, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/kalbach_mann.py b/openmc/data/kalbach_mann.py index de9809df3a..30a1c01cdc 100644 --- a/openmc/data/kalbach_mann.py +++ b/openmc/data/kalbach_mann.py @@ -53,7 +53,7 @@ class KalbachMann(AngleEnergy): def __init__(self, breakpoints, interpolation, energy, energy_out, precompound, slope): - super(KalbachMann, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/laboratory.py b/openmc/data/laboratory.py index 3c240b88d1..18516d9b87 100644 --- a/openmc/data/laboratory.py +++ b/openmc/data/laboratory.py @@ -44,7 +44,7 @@ class LaboratoryAngleEnergy(AngleEnergy): """ def __init__(self, breakpoints, interpolation, energy, mu, energy_out): - super(LaboratoryAngleEnergy, self).__init__() + super().__init__() self.breakpoints = breakpoints self.interpolation = interpolation self.energy = energy diff --git a/openmc/data/resonance.py b/openmc/data/resonance.py index 8feda92df4..5e7e0c44d7 100644 --- a/openmc/data/resonance.py +++ b/openmc/data/resonance.py @@ -288,8 +288,8 @@ class MultiLevelBreitWigner(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(MultiLevelBreitWigner, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) self.parameters = None self.q_value = {} self.atomic_weight_ratio = None @@ -490,8 +490,8 @@ class SingleLevelBreitWigner(MultiLevelBreitWigner): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(SingleLevelBreitWigner, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) # Set resonance reconstruction function if _reconstruct: @@ -549,8 +549,8 @@ class ReichMoore(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, channel, scattering): - super(ReichMoore, self).__init__( - target_spin, energy_min, energy_max, channel, scattering) + super().__init__(target_spin, energy_min, energy_max, channel, + scattering) self.parameters = None self.angle_distribution = False self.num_l_convergence = 0 @@ -724,8 +724,7 @@ class RMatrixLimited(ResonanceRange): """ def __init__(self, energy_min, energy_max, particle_pairs, spin_groups): - super(RMatrixLimited, self).__init__(0.0, energy_min, energy_max, - None, None) + super().__init__(0.0, energy_min, energy_max, None, None) self.reduced_width = False self.formalism = 3 self.particle_pairs = particle_pairs @@ -931,8 +930,7 @@ class Unresolved(ResonanceRange): """ def __init__(self, target_spin, energy_min, energy_max, scatter): - super(Unresolved, self).__init__( - target_spin, energy_min, energy_max, None, scatter) + super().__init__(target_spin, energy_min, energy_max, None, scatter) self.energies = None self.parameters = None self.add_to_background = False diff --git a/openmc/element.py b/openmc/element.py index 25cb97538c..336d1f028b 100644 --- a/openmc/element.py +++ b/openmc/element.py @@ -29,7 +29,7 @@ class Element(str): def __new__(cls, name): cv.check_type('element name', name, str) cv.check_length('element name', name, 1, 2) - return super(Element, cls).__new__(cls, name) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/filter.py b/openmc/filter.py index 8f57a80906..8763515f4e 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -64,8 +64,7 @@ class FilterMeta(ABCMeta): namespace[func_name].__doc__ = old_doc # Make the class. - return super(FilterMeta, cls).__new__(cls, name, bases, namespace, - **kwargs) + return super().__new__(cls, name, bases, namespace, **kwargs) class Filter(IDManagerMixin, metaclass=FilterMeta): @@ -672,7 +671,7 @@ class MeshFilter(Filter): def __init__(self, mesh, filter_id=None): self.mesh = mesh - super(MeshFilter, self).__init__(mesh.id, filter_id) + super().__init__(mesh.id, filter_id) @classmethod def from_hdf5(cls, group, **kwargs): @@ -869,7 +868,7 @@ class RealFilter(Filter): # This logic is used when merging tallies with real filters return self.bins[0] >= other.bins[-1] else: - return super(RealFilter, self).__gt__(other) + return super().__gt__(other) @property def num_bins(self): @@ -1127,7 +1126,7 @@ class DistribcellFilter(Filter): def __init__(self, cell, filter_id=None): self._paths = None - super(DistribcellFilter, self).__init__(cell, filter_id) + super().__init__(cell, filter_id) @classmethod def from_hdf5(cls, group, **kwargs): diff --git a/openmc/lattice.py b/openmc/lattice.py index 1bb82f6284..0819a85917 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -489,7 +489,7 @@ class RectLattice(Lattice): """ def __init__(self, lattice_id=None, name=''): - super(RectLattice, self).__init__(lattice_id, name) + super().__init__(lattice_id, name) # Initialize Lattice class attributes self._lower_left = None @@ -820,7 +820,7 @@ class HexLattice(Lattice): """ def __init__(self, lattice_id=None, name=''): - super(HexLattice, self).__init__(lattice_id, name) + super().__init__(lattice_id, name) # Initialize Lattice class attributes self._num_rings = None diff --git a/openmc/macroscopic.py b/openmc/macroscopic.py index f5bd90f3a4..2a5a22752a 100644 --- a/openmc/macroscopic.py +++ b/openmc/macroscopic.py @@ -18,7 +18,7 @@ class Macroscopic(str): def __new__(cls, name): check_type('name', name, str) - return super(Macroscopic, cls).__new__(cls, name) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/material.py b/openmc/material.py index cb3024447b..a3fa854533 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -885,7 +885,7 @@ class Materials(cv.CheckedList): """ def __init__(self, materials=None): - super(Materials, self).__init__(Material, 'materials collection') + super().__init__(Material, 'materials collection') self._cross_sections = None self._multipole_library = None @@ -954,7 +954,7 @@ class Materials(cv.CheckedList): Material to append """ - super(Materials, self).append(material) + super().append(material) def insert(self, index, material): """Insert material before index @@ -967,7 +967,7 @@ class Materials(cv.CheckedList): Material to insert """ - super(Materials, self).insert(index, material) + super().insert(index, material) def remove_material(self, material): """Remove a material from the file diff --git a/openmc/mgxs/mdgxs.py b/openmc/mgxs/mdgxs.py index 7799183ff7..dfd0d192d9 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -129,8 +129,8 @@ class MDGXS(MGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(MDGXS, self).__init__(domain, domain_type, energy_groups, - by_nuclide, name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, by_nuclide, name, + num_polar, num_azimuthal) self._delayed_groups = None @@ -547,7 +547,7 @@ class MDGXS(MGXS): """ - merged_mdgxs = super(MDGXS, self).merge(other) + merged_mdgxs = super().merge(other) # Merge delayed groups if self.delayed_groups != other.delayed_groups: @@ -577,7 +577,7 @@ class MDGXS(MGXS): """ if self.delayed_groups is None: - super(MDGXS, self).print_xs(subdomains, nuclides, xs_type) + super().print_xs(subdomains, nuclides, xs_type) return # Construct a collection of the subdomains to report @@ -1007,9 +1007,8 @@ class ChiDelayed(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(ChiDelayed, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'chi-delayed' self._estimator = 'analog' @@ -1055,7 +1054,7 @@ class ChiDelayed(MDGXS): # Compute chi self._xs_tally = self.rxn_rate_tally / delayed_nu_fission_in - super(ChiDelayed, self)._compute_xs() + super()._compute_xs() # Add the coarse energy filter back to the nu-fission tally delayed_nu_fission_in.filters.append(energy_filter) @@ -1127,8 +1126,7 @@ class ChiDelayed(MDGXS): delayed_nu_fission_in.remove_filter(energy_filter) # Call super class method and null out derived tallies - slice_xs = super(ChiDelayed, self).get_slice(nuclides, groups, - delayed_groups) + slice_xs = super().get_slice(nuclides, groups, delayed_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -1521,10 +1519,8 @@ class DelayedNuFissionXS(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DelayedNuFissionXS, self).__init__(domain, domain_type, - energy_groups, delayed_groups, - by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'delayed-nu-fission' @@ -1657,9 +1653,8 @@ class Beta(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(Beta, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'beta' @property @@ -1685,7 +1680,7 @@ class Beta(MDGXS): # Compute beta self._xs_tally = self.rxn_rate_tally / nu_fission - super(Beta, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -1841,9 +1836,8 @@ class DecayRate(MDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DecayRate, self).__init__(domain, domain_type, energy_groups, - delayed_groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'decay-rate' @property @@ -1878,7 +1872,7 @@ class DecayRate(MDGXS): # Compute the decay rate self._xs_tally = self.rxn_rate_tally / delayed_nu_fission - super(DecayRate, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -2261,8 +2255,7 @@ class MatrixMDGXS(MDGXS): """ # Call super class method and null out derived tallies - slice_xs = super(MatrixMDGXS, self).get_slice(nuclides, in_groups, - delayed_groups) + slice_xs = super().get_slice(nuclides, in_groups, delayed_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -2609,12 +2602,8 @@ class DelayedNuFissionMatrixXS(MatrixMDGXS): def __init__(self, domain=None, domain_type=None, energy_groups=None, delayed_groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(DelayedNuFissionMatrixXS, self).__init__(domain, domain_type, - energy_groups, - delayed_groups, - by_nuclide, name, - num_polar, - num_azimuthal) + super().__init__(domain, domain_type, energy_groups, delayed_groups, + by_nuclide, name, num_polar, num_azimuthal) self._rxn_type = 'delayed-nu-fission' self._hdf5_key = 'delayed-nu-fission matrix' self._estimator = 'analog' diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index 949f0fba00..ecedc8e63a 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -2292,7 +2292,7 @@ class MatrixMGXS(MGXS): """ # Call super class method and null out derived tallies - slice_xs = super(MatrixMGXS, self).get_slice(nuclides, in_groups) + slice_xs = super().get_slice(nuclides, in_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -2567,9 +2567,8 @@ class TotalXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(TotalXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'total' @@ -2704,9 +2703,8 @@ class TransportXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, nu=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(TransportXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) # Use tracklength estimators for the total MGXS term, and # analog estimators for the transport correction term @@ -2715,7 +2713,7 @@ class TransportXS(MGXS): self.nu = nu def __deepcopy__(self, memo): - clone = super(TransportXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu return clone @@ -2912,9 +2910,8 @@ class AbsorptionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(AbsorptionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'absorption' @@ -3039,9 +3036,8 @@ class CaptureXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(CaptureXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'capture' @property @@ -3194,16 +3190,15 @@ class FissionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, nu=False, prompt=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(FissionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._nu = False self._prompt = False self.nu = nu self.prompt = prompt def __deepcopy__(self, memo): - clone = super(FissionXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu clone._prompt = self.prompt return clone @@ -3362,9 +3357,8 @@ class KappaFissionXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(KappaFissionXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'kappa-fission' @@ -3495,13 +3489,12 @@ class ScatterXS(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, nu=False): - super(ScatterXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self.nu = nu def __deepcopy__(self, memo): - clone = super(ScatterXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._nu = self.nu return clone @@ -3712,9 +3705,8 @@ class ScatterMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, nu=False): - super(ScatterMatrixXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._formulation = 'simple' self._correction = 'P0' self._scatter_format = 'legendre' @@ -3725,7 +3717,7 @@ class ScatterMatrixXS(MatrixMGXS): self.nu = nu def __deepcopy__(self, memo): - clone = super(ScatterMatrixXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._formulation = self.formulation clone._correction = self.correction clone._scatter_format = self.scatter_format @@ -3816,7 +3808,7 @@ class ScatterMatrixXS(MatrixMGXS): @property def tally_keys(self): if self.formulation == 'simple': - return super(ScatterMatrixXS, self).tally_keys + return super().tally_keys else: # Add keys for groupwise scattering cross section tally_keys = ['flux (tracklength)', 'scatter'] @@ -4146,7 +4138,7 @@ class ScatterMatrixXS(MatrixMGXS): [score_prefix + '{}'.format(i) for i in range(self.legendre_order + 1)] - super(ScatterMatrixXS, self).load_from_statepoint(statepoint) + super().load_from_statepoint(statepoint) def get_slice(self, nuclides=[], in_groups=[], out_groups=[], legendre_order='same'): @@ -4186,7 +4178,7 @@ class ScatterMatrixXS(MatrixMGXS): """ # Call super class method and null out derived tallies - slice_xs = super(ScatterMatrixXS, self).get_slice(nuclides, in_groups) + slice_xs = super().get_slice(nuclides, in_groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -4477,8 +4469,7 @@ class ScatterMatrixXS(MatrixMGXS): """ - df = super(ScatterMatrixXS, self).get_pandas_dataframe( - groups, nuclides, xs_type, paths) + df = super().get_pandas_dataframe(groups, nuclides, xs_type, paths) if self.scatter_format == 'legendre': # Add a moment column to dataframe @@ -4802,9 +4793,8 @@ class MultiplicityMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(MultiplicityMatrixXS, self).__init__(domain, domain_type, groups, - by_nuclide, name, num_polar, - num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'multiplicity matrix' self._estimator = 'analog' self._valid_estimators = ['analog'] @@ -4839,7 +4829,7 @@ class MultiplicityMatrixXS(MatrixMGXS): # Compute the multiplicity self._xs_tally = self.rxn_rate_tally / scatter - super(MultiplicityMatrixXS, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -4968,9 +4958,8 @@ class ScatterProbabilityMatrix(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(ScatterProbabilityMatrix, self).__init__( - domain, domain_type, groups, by_nuclide, - name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, + name, num_polar, num_azimuthal) self._rxn_type = 'scatter' self._hdf5_key = 'scatter probability matrix' @@ -5012,7 +5001,7 @@ class ScatterProbabilityMatrix(MatrixMGXS): # Compute the group-to-group probabilities self._xs_tally = self.tallies[self.rxn_type] / norm - super(ScatterProbabilityMatrix, self)._compute_xs() + super()._compute_xs() return self._xs_tally @@ -5142,9 +5131,8 @@ class NuFissionMatrixXS(MatrixMGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1, prompt=False): - super(NuFissionMatrixXS, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) if not prompt: self._rxn_type = 'nu-fission' self._hdf5_key = 'nu-fission matrix' @@ -5165,7 +5153,7 @@ class NuFissionMatrixXS(MatrixMGXS): self._prompt = prompt def __deepcopy__(self, memo): - clone = super(NuFissionMatrixXS, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._prompt = self.prompt return clone @@ -5299,8 +5287,8 @@ class Chi(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, prompt=False, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(Chi, self).__init__(domain, domain_type, groups, by_nuclide, - name, num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) if not prompt: self._rxn_type = 'chi' else: @@ -5310,7 +5298,7 @@ class Chi(MGXS): self.prompt = prompt def __deepcopy__(self, memo): - clone = super(Chi, self).__deepcopy__(memo) + clone = super().__deepcopy__(memo) clone._prompt = self.prompt return clone @@ -5440,7 +5428,7 @@ class Chi(MGXS): 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 = super().get_slice(nuclides, groups) slice_xs._rxn_rate_tally = None slice_xs._xs_tally = None @@ -5718,8 +5706,7 @@ class Chi(MGXS): """ # Build the dataframe using the parent class method - df = super(Chi, self).get_pandas_dataframe( - groups, nuclides, xs_type, paths=paths) + df = super().get_pandas_dataframe(groups, nuclides, xs_type, paths=paths) # If user requested micro cross sections, multiply by the atom # densities to cancel out division made by the parent class method @@ -5877,9 +5864,8 @@ class InverseVelocity(MGXS): def __init__(self, domain=None, domain_type=None, groups=None, by_nuclide=False, name='', num_polar=1, num_azimuthal=1): - super(InverseVelocity, self).__init__(domain, domain_type, - groups, by_nuclide, name, - num_polar, num_azimuthal) + super().__init__(domain, domain_type, groups, by_nuclide, name, + num_polar, num_azimuthal) self._rxn_type = 'inverse-velocity' def get_units(self, xs_type='macro'): diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 0fe138bd70..fab2f54cc1 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -45,7 +45,7 @@ class TRISO(openmc.Cell): def __init__(self, outer_radius, fill, center=(0., 0., 0.)): self._surface = openmc.Sphere(R=outer_radius) - super(TRISO, self).__init__(fill=fill, region=-self._surface) + super().__init__(fill=fill, region=-self._surface) self.center = np.asarray(center) @property @@ -245,7 +245,7 @@ class _CubicDomain(_Domain): """ def __init__(self, length, particle_radius, center=[0., 0., 0.]): - super(_CubicDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.length = length @property @@ -324,7 +324,7 @@ class _CylindricalDomain(_Domain): """ def __init__(self, length, radius, particle_radius, center=[0., 0., 0.]): - super(_CylindricalDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.length = length self.radius = radius @@ -414,7 +414,7 @@ class _SphericalDomain(_Domain): """ def __init__(self, radius, particle_radius, center=[0., 0., 0.]): - super(_SphericalDomain, self).__init__(particle_radius, center) + super().__init__(particle_radius, center) self.radius = radius @property diff --git a/openmc/nuclide.py b/openmc/nuclide.py index 73247e1aa2..f7c725040f 100644 --- a/openmc/nuclide.py +++ b/openmc/nuclide.py @@ -32,7 +32,7 @@ class Nuclide(str): '"{}" is being renamed as "{}".'.format(orig_name, name) warnings.warn(msg) - return super(Nuclide, cls).__new__(cls, name) + return super().__new__(cls, name) @property def name(self): diff --git a/openmc/plots.py b/openmc/plots.py index bfff2d7e90..44d68d72f2 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -673,7 +673,7 @@ class Plots(cv.CheckedList): """ def __init__(self, plots=None): - super(Plots, self).__init__(Plot, 'plots collection') + super().__init__(Plot, 'plots collection') self._plots_file = ET.Element("plots") if plots is not None: self += plots @@ -704,7 +704,7 @@ class Plots(cv.CheckedList): Plot to append """ - super(Plots, self).append(plot) + super().append(plot) def insert(self, index, plot): """Insert plot before index @@ -717,7 +717,7 @@ class Plots(cv.CheckedList): Plot to insert """ - super(Plots, self).insert(index, plot) + super().insert(index, plot) def remove_plot(self, plot): """Remove a plot from the file. diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index ba2debaeaf..1fe883866f 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -75,7 +75,7 @@ class PolarAzimuthal(UnitSphere): """ def __init__(self, mu=None, phi=None, reference_uvw=[0., 0., 1.]): - super(PolarAzimuthal, self).__init__(reference_uvw) + super().__init__(reference_uvw) if mu is not None: self.mu = mu else: @@ -128,7 +128,7 @@ class Isotropic(UnitSphere): """ def __init__(self): - super(Isotropic, self).__init__() + super().__init__() def to_xml_element(self): """Return XML representation of the isotropic distribution @@ -161,7 +161,7 @@ class Monodirectional(UnitSphere): def __init__(self, reference_uvw=[1., 0., 0.]): - super(Monodirectional, self).__init__(reference_uvw) + super().__init__(reference_uvw) def to_xml_element(self): """Return XML representation of the monodirectional distribution @@ -222,7 +222,7 @@ class CartesianIndependent(Spatial): def __init__(self, x, y, z): - super(CartesianIndependent, self).__init__() + super().__init__() self.x = x self.y = y self.z = z @@ -298,7 +298,7 @@ class Box(Spatial): def __init__(self, lower_left, upper_right, only_fissionable=False): - super(Box, self).__init__() + super().__init__() self.lower_left = lower_left self.upper_right = upper_right self.only_fissionable = only_fissionable @@ -371,7 +371,7 @@ class Point(Spatial): """ def __init__(self, xyz=(0., 0., 0.)): - super(Point, self).__init__() + super().__init__() self.xyz = xyz @property diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index 47a281d213..6996970af1 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -57,7 +57,7 @@ class Discrete(Univariate): """ def __init__(self, x, p): - super(Discrete, self).__init__() + super().__init__() self.x = x self.p = p @@ -131,7 +131,7 @@ class Uniform(Univariate): """ def __init__(self, a=0.0, b=1.0): - super(Uniform, self).__init__() + super().__init__() self.a = a self.b = b @@ -202,7 +202,7 @@ class Maxwell(Univariate): """ def __init__(self, theta): - super(Maxwell, self).__init__() + super().__init__() self.theta = theta def __len__(self): @@ -262,7 +262,7 @@ class Watt(Univariate): """ def __init__(self, a=0.988e6, b=2.249e-6): - super(Watt, self).__init__() + super().__init__() self.a = a self.b = b @@ -342,7 +342,7 @@ class Tabular(Univariate): def __init__(self, x, p, interpolation='linear-linear', ignore_negative=False): - super(Tabular, self).__init__() + super().__init__() self._ignore_negative = ignore_negative self.x = x self.p = p @@ -470,7 +470,7 @@ class Mixture(Univariate): """ def __init__(self, probability, distribution): - super(Mixture, self).__init__() + super().__init__() self.probability = probability self.distribution = distribution diff --git a/openmc/surface.py b/openmc/surface.py index 694e9fd221..ad5053e370 100644 --- a/openmc/surface.py +++ b/openmc/surface.py @@ -326,7 +326,7 @@ class Plane(Surface): def __init__(self, surface_id=None, boundary_type='transmission', A=1., B=0., C=0., D=0., name=''): - super(Plane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'plane' self._coeff_keys = ['A', 'B', 'C', 'D'] @@ -410,7 +410,7 @@ class Plane(Surface): XML element containing source data """ - element = super(Plane, self).to_xml_element() + element = super().to_xml_element() # Add periodic surface pair information if self.boundary_type == 'periodic': @@ -460,7 +460,7 @@ class XPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., name=''): - super(XPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'x-plane' self._coeff_keys = ['x0'] @@ -566,7 +566,7 @@ class YPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', y0=0., name=''): # Initialize YPlane class attributes - super(YPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'y-plane' self._coeff_keys = ['y0'] @@ -672,7 +672,7 @@ class ZPlane(Plane): def __init__(self, surface_id=None, boundary_type='transmission', z0=0., name=''): # Initialize ZPlane class attributes - super(ZPlane, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'z-plane' self._coeff_keys = ['z0'] @@ -773,7 +773,7 @@ class Cylinder(Surface, metaclass=ABCMeta): """ def __init__(self, surface_id=None, boundary_type='transmission', R=1., name=''): - super(Cylinder, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._coeff_keys = ['R'] self.r = R @@ -833,7 +833,7 @@ class XCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', y0=0., z0=0., R=1., name=''): - super(XCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'x-cylinder' self._coeff_keys = ['y0', 'z0', 'R'] @@ -955,7 +955,7 @@ class YCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., z0=0., R=1., name=''): - super(YCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'y-cylinder' self._coeff_keys = ['x0', 'z0', 'R'] @@ -1077,7 +1077,7 @@ class ZCylinder(Cylinder): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., R=1., name=''): - super(ZCylinder, self).__init__(surface_id, boundary_type, R, name=name) + super().__init__(surface_id, boundary_type, R, name=name) self._type = 'z-cylinder' self._coeff_keys = ['x0', 'y0', 'R'] @@ -1203,7 +1203,7 @@ class Sphere(Surface): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R=1., name=''): - super(Sphere, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'sphere' self._coeff_keys = ['x0', 'y0', 'z0', 'R'] @@ -1350,7 +1350,7 @@ class Cone(Surface, metaclass=ABCMeta): """ def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(Cone, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._coeff_keys = ['x0', 'y0', 'z0', 'R2'] self.x0 = x0 @@ -1445,7 +1445,7 @@ class XCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(XCone, self).__init__(surface_id, boundary_type, x0, y0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'x-cone' @@ -1521,7 +1521,7 @@ class YCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(YCone, self).__init__(surface_id, boundary_type, x0, y0, z0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'y-cone' @@ -1597,7 +1597,7 @@ class ZCone(Cone): def __init__(self, surface_id=None, boundary_type='transmission', x0=0., y0=0., z0=0., R2=1., name=''): - super(ZCone, self).__init__(surface_id, boundary_type, x0, y0, z0, + super().__init__(surface_id, boundary_type, x0, y0, z0, R2, name=name) self._type = 'z-cone' @@ -1662,7 +1662,7 @@ class Quadric(Surface): def __init__(self, surface_id=None, boundary_type='transmission', a=0., b=0., c=0., d=0., e=0., f=0., g=0., h=0., j=0., k=0., name=''): - super(Quadric, self).__init__(surface_id, boundary_type, name=name) + super().__init__(surface_id, boundary_type, name=name) self._type = 'quadric' self._coeff_keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k'] diff --git a/openmc/tallies.py b/openmc/tallies.py index 17c298a8db..e838de6655 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -3242,7 +3242,7 @@ class Tallies(cv.CheckedList): """ def __init__(self, tallies=None): - super(Tallies, self).__init__(Tally, 'tallies collection') + super().__init__(Tally, 'tallies collection') if tallies is not None: self += tallies @@ -3299,10 +3299,10 @@ class Tallies(cv.CheckedList): # If no mergeable tally was found, simply add this tally if not merged: - super(Tallies, self).append(tally) + super().append(tally) else: - super(Tallies, self).append(tally) + super().append(tally) def insert(self, index, item): """Insert tally before index @@ -3315,7 +3315,7 @@ class Tallies(cv.CheckedList): Tally to insert """ - super(Tallies, self).insert(index, item) + super().insert(index, item) def remove_tally(self, tally): """Remove a tally from the collection From 7263d80c2c231ac35325ebb7bae35569589c10a1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 24 Dec 2017 16:36:59 +0700 Subject: [PATCH 081/212] Update installation instructions --- docs/source/usersguide/install.rst | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 638d425014..9b11d1dce4 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -385,8 +385,7 @@ Python package in the same location as the ``openmc`` executable (for example, if you are installing the package into a `virtual environment `_). The easiest way to install the :mod:`openmc` Python package is to use pip_, which is included by default in -Python 2.7 and Python 3.4+. From the root directory of the OpenMC -distribution/repository, run: +Python 3.4+. From the root directory of the OpenMC distribution/repository, run: .. code-block:: sh @@ -414,18 +413,14 @@ to install the Python package in :ref:`"editable" mode `. Prerequisites ------------- -The Python API works with either Python 2.7 or Python 3.2+. In addition to -Python itself, the API relies on a number of third-party packages. All -prerequisites can be installed using Conda_ (recommended), pip_, or through the -package manager in most Linux distributions. +The Python API works with Python 3.4+. In addition to Python itself, the API +relies on a number of third-party packages. All prerequisites can be installed +using Conda_ (recommended), pip_, or through the package manager in most Linux +distributions. .. admonition:: Required :class: error - `six `_ - The Python API works with both Python 2.7+ and 3.2+. To do so, the six - compatibility library is used. - `NumPy `_ NumPy is used extensively within the Python API for its powerful N-dimensional array. From 0aee52c5ab8ad077e20542a832a6aaccf34f48e1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 29 Dec 2017 14:03:11 -0600 Subject: [PATCH 082/212] Remove deprecated methods --- openmc/cell.py | 44 ------ openmc/material.py | 52 ------- openmc/plots.py | 34 ----- openmc/settings.py | 49 ------- openmc/tallies.py | 167 ---------------------- openmc/trigger.py | 17 --- tests/regression_tests/diff_tally/test.py | 36 ++--- 7 files changed, 13 insertions(+), 386 deletions(-) diff --git a/openmc/cell.py b/openmc/cell.py index 087f2816d4..838d419b62 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -283,50 +283,6 @@ class Cell(IDManagerMixin): cv.check_type('cell volume', volume, Real) self._volume = volume - def add_surface(self, surface, halfspace): - """Add a half-space to the list of half-spaces whose intersection defines the - cell. - - .. deprecated:: 0.7.1 - Use the :attr:`Cell.region` property to directly specify a Region - expression. - - Parameters - ---------- - surface : openmc.Surface - Quadric surface dividing space - halfspace : {-1, 1} - Indicate whether the negative or positive half-space is to be used - - """ - - warnings.warn("Cell.add_surface(...) has been deprecated and may be " - "removed in a future version. The region for a Cell " - "should be defined using the region property directly.", - DeprecationWarning) - - if not isinstance(surface, openmc.Surface): - msg = 'Unable to add Surface "{0}" to Cell ID="{1}" since it is ' \ - 'not a Surface object'.format(surface, self._id) - raise ValueError(msg) - - if halfspace not in [-1, +1]: - msg = 'Unable to add Surface "{0}" to Cell ID="{1}" with halfspace ' \ - '"{2}" since it is not +/-1'.format(surface, self._id, halfspace) - raise ValueError(msg) - - # If no region has been assigned, simply use the half-space. Otherwise, - # take the intersection of the current region and the half-space - # specified - region = +surface if halfspace == 1 else -surface - if self.region is None: - self.region = region - else: - if isinstance(self.region, Intersection): - self.region &= region - else: - self.region = Intersection(self.region, region) - def add_volume_information(self, volume_calc): """Add volume information to a cell. diff --git a/openmc/material.py b/openmc/material.py index a3fa854533..e409d6536c 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -910,41 +910,6 @@ class Materials(cv.CheckedList): cv.check_type('cross sections', multipole_library, str) self._multipole_library = multipole_library - def add_material(self, material): - """Append material to collection - - .. deprecated:: 0.8 - Use :meth:`Materials.append` instead. - - Parameters - ---------- - material : openmc.Material - Material to add - - """ - warnings.warn("Materials.add_material(...) has been deprecated and may be " - "removed in a future version. Use Material.append(...) " - "instead.", DeprecationWarning) - self.append(material) - - def add_materials(self, materials): - """Add multiple materials to the collection - - .. deprecated:: 0.8 - Use compound assignment instead. - - Parameters - ---------- - materials : Iterable of openmc.Material - Materials to add - - """ - warnings.warn("Materials.add_materials(...) has been deprecated and may be " - "removed in a future version. Use compound assignment " - "instead.", DeprecationWarning) - for material in materials: - self.append(material) - def append(self, material): """Append material to collection @@ -969,23 +934,6 @@ class Materials(cv.CheckedList): """ super().insert(index, material) - def remove_material(self, material): - """Remove a material from the file - - .. deprecated:: 0.8 - Use :meth:`Materials.remove` instead. - - Parameters - ---------- - material : openmc.Material - Material to remove - - """ - warnings.warn("Materials.remove_material(...) has been deprecated and " - "may be removed in a future version. Use " - "Materials.remove(...) instead.", DeprecationWarning) - self.remove(material) - def make_isotropic_in_lab(self): for material in self: material.make_isotropic_in_lab() diff --git a/openmc/plots.py b/openmc/plots.py index 44d68d72f2..159e920780 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -678,23 +678,6 @@ class Plots(cv.CheckedList): if plots is not None: self += plots - def add_plot(self, plot): - """Add a plot to the file. - - .. deprecated:: 0.8 - Use :meth:`Plots.append` instead. - - Parameters - ---------- - plot : openmc.Plot - Plot to add - - """ - warnings.warn("Plots.add_plot(...) has been deprecated and may be " - "removed in a future version. Use Plots.append(...) " - "instead.", DeprecationWarning) - self.append(plot) - def append(self, plot): """Append plot to collection @@ -719,23 +702,6 @@ class Plots(cv.CheckedList): """ super().insert(index, plot) - def remove_plot(self, plot): - """Remove a plot from the file. - - .. deprecated:: 0.8 - Use :meth:`Plots.remove` instead. - - Parameters - ---------- - plot : openmc.Plot - Plot to remove - - """ - warnings.warn("Plots.remove_plot(...) has been deprecated and may be " - "removed in a future version. Use Plots.remove(...) " - "instead.", DeprecationWarning) - self.remove(plot) - def colorize(self, geometry, seed=1): """Generate a consistent color scheme for each domain in each plot. diff --git a/openmc/settings.py b/openmc/settings.py index 1bbc7a4ec3..b9562b7ddc 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -28,13 +28,6 @@ class Settings(object): deviation. create_fission_neutrons : bool Indicate whether fission neutrons should be created or not. - cross_sections : str - Indicates the path to an XML cross section listing file (usually named - cross_sections.xml). If it is not set, the - :envvar:`OPENMC_CROSS_SECTIONS` environment variable will be used for - continuous-energy calculations and - :envvar:`OPENMC_MG_CROSS_SECTIONS` will be used for multi-group - calculations to find the path to the XML cross section file. cutoff : dict Dictionary defining weight cutoff and energy cutoff. The dictionary may have three keys, 'weight', 'weight_avg' and 'energy'. Value for 'weight' @@ -63,11 +56,6 @@ class Settings(object): Number of bins for logarithmic energy grid search max_order : None or int Maximum scattering order to apply globally when in multi-group mode. - multipole_library : str - Indicates the path to a directory containing a windowed multipole - cross section library. If it is not set, the - :envvar:`OPENMC_MULTIPOLE_LIBRARY` environment variable will be used. A - multipole library is optional. no_reduce : bool Indicate that all user-defined and global tallies should not be reduced across processes in a parallel calculation. @@ -268,14 +256,6 @@ class Settings(object): def confidence_intervals(self): return self._confidence_intervals - @property - def cross_sections(self): - return self._cross_sections - - @property - def multipole_library(self): - return self._multipole_library - @property def ptables(self): return self._ptables @@ -505,23 +485,6 @@ class Settings(object): cv.check_type('confidence interval', confidence_intervals, bool) self._confidence_intervals = confidence_intervals - @cross_sections.setter - def cross_sections(self, cross_sections): - warnings.warn('Settings.cross_sections has been deprecated and will be ' - 'removed in a future version. Materials.cross_sections ' - 'should defined instead.', DeprecationWarning) - cv.check_type('cross sections', cross_sections, str) - self._cross_sections = cross_sections - - @multipole_library.setter - def multipole_library(self, multipole_library): - warnings.warn('Settings.multipole_library has been deprecated and will ' - 'be removed in a future version. ' - 'Materials.multipole_library should defined instead.', - DeprecationWarning) - cv.check_type('multipole library', multipole_library, str) - self._multipole_library = multipole_library - @ptables.setter def ptables(self, ptables): cv.check_type('probability tables', ptables, bool) @@ -814,16 +777,6 @@ class Settings(object): element = ET.SubElement(root, "confidence_intervals") element.text = str(self._confidence_intervals).lower() - def _create_cross_sections_subelement(self, root): - if self._cross_sections is not None: - element = ET.SubElement(root, "cross_sections") - element.text = str(self._cross_sections) - - def _create_multipole_library_subelement(self, root): - if self._multipole_library is not None: - element = ET.SubElement(root, "multipole_library") - element.text = str(self._multipole_library) - def _create_ptables_subelement(self, root): if self._ptables is not None: element = ET.SubElement(root, "ptables") @@ -988,8 +941,6 @@ class Settings(object): self._create_statepoint_subelement(root_element) self._create_sourcepoint_subelement(root_element) self._create_confidence_intervals(root_element) - self._create_cross_sections_subelement(root_element) - self._create_multipole_library_subelement(root_element) self._create_energy_mode_subelement(root_element) self._create_max_order_subelement(root_element) self._create_ptables_subelement(root_element) diff --git a/openmc/tallies.py b/openmc/tallies.py index e838de6655..61be38fb2a 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -332,26 +332,6 @@ class Tally(IDManagerMixin): self._triggers = cv.CheckedList(openmc.Trigger, 'tally triggers', triggers) - def add_trigger(self, trigger): - """Add a tally trigger to the tally - - .. deprecated:: 0.8 - Use the Tally.triggers property directly, i.e., - Tally.triggers.append(...) - - Parameters - ---------- - trigger : openmc.Trigger - Trigger to add - - """ - - warnings.warn('Tally.add_trigger(...) has been deprecated and may be ' - 'removed in a future version. Tally triggers should be ' - 'defined using the triggers property directly.', - DeprecationWarning) - self.triggers.append(trigger) - @name.setter def name(self, name): if name is not None: @@ -413,80 +393,6 @@ class Tally(IDManagerMixin): self._scores = cv.CheckedList(_SCORE_CLASSES, 'tally scores', scores) - def add_filter(self, new_filter): - """Add a filter to the tally - - .. deprecated:: 0.8 - Use the Tally.filters property directly, i.e., - Tally.filters.append(...) - - Parameters - ---------- - new_filter : Filter, CrossFilter or AggregateFilter - A filter to specify a discretization of the tally across some - dimension (e.g., 'energy', 'cell'). The filter should be a Filter - object when a user is adding filters to a Tally for input file - generation or when the Tally is created from a StatePoint. The - filter may be a CrossFilter or AggregateFilter for derived tallies - created by tally arithmetic. - - """ - - warnings.warn('Tally.add_filter(...) has been deprecated and may be ' - 'removed in a future version. Tally filters should be ' - 'defined using the filters property directly.', - DeprecationWarning) - self.filters.append(new_filter) - - def add_nuclide(self, nuclide): - """Specify that scores for a particular nuclide should be accumulated - - .. deprecated:: 0.8 - Use the Tally.nuclides property directly, i.e., - Tally.nuclides.append(...) - - Parameters - ---------- - nuclide : str, openmc.Nuclide, CrossNuclide or AggregateNuclide - Nuclide to add to the tally. The nuclide should be a Nuclide object - when a user is adding nuclides to a Tally for input file generation. - The nuclide is a str when a Tally is created from a StatePoint file - (e.g., 'H1', 'U235') unless a Summary has been linked with the - StatePoint. The nuclide may be a CrossNuclide or AggregateNuclide - for derived tallies created by tally arithmetic. - - """ - - warnings.warn('Tally.add_nuclide(...) has been deprecated and may be ' - 'removed in a future version. Tally nuclides should be ' - 'defined using the nuclides property directly.', - DeprecationWarning) - self.nuclides.append(nuclide) - - def add_score(self, score): - """Specify a quantity to be scored - - .. deprecated:: 0.8 - Use the Tally.scores property directly, i.e., - Tally.scores.append(...) - - Parameters - ---------- - score : str, CrossScore or AggregateScore - A score to be accumulated (e.g., 'flux', 'nu-fission'). The score - should be a str when a user is adding scores to a Tally for input - file generation or when the Tally is created from a StatePoint. The - score may be a CrossScore or AggregateScore for derived tallies - created by tally arithmetic. - - """ - - warnings.warn('Tally.add_score(...) has been deprecated and may be ' - 'removed in a future version. Tally scores should be ' - 'defined using the scores property directly.', - DeprecationWarning) - self.scores.append(score) - @num_realizations.setter def num_realizations(self, num_realizations): cv.check_type('number of realizations', num_realizations, Integral) @@ -3246,26 +3152,6 @@ class Tallies(cv.CheckedList): if tallies is not None: self += tallies - def add_tally(self, tally, merge=False): - """Append tally to collection - - .. deprecated:: 0.8 - Use :meth:`Tallies.append` instead. - - Parameters - ---------- - tally : openmc.Tally - Tally to add - merge : bool - Indicate whether the tally should be merged with an existing tally, - if possible. Defaults to False. - - """ - warnings.warn("Tallies.add_tally(...) has been deprecated and may be " - "removed in a future version. Use Tallies.append(...) " - "instead.", DeprecationWarning) - self.append(tally, merge) - def append(self, tally, merge=False): """Append tally to collection @@ -3317,24 +3203,6 @@ class Tallies(cv.CheckedList): """ super().insert(index, item) - def remove_tally(self, tally): - """Remove a tally from the collection - - .. deprecated:: 0.8 - Use :meth:`Tallies.remove` instead. - - Parameters - ---------- - tally : openmc.Tally - Tally to remove - - """ - warnings.warn("Tallies.remove_tally(...) has been deprecated and may " - "be removed in a future version. Use Tallies.remove(...) " - "instead.", DeprecationWarning) - - self.remove(tally) - def merge_tallies(self): """Merge any mergeable tallies together. Note that n-way merges are possible. @@ -3359,41 +3227,6 @@ class Tallies(cv.CheckedList): # Continue iterating from the first loop break - def add_mesh(self, mesh): - """Add a mesh to the file - - .. deprecated:: 0.8 - Meshes that appear in a tally are automatically added to the - collection. - - Parameters - ---------- - mesh : openmc.Mesh - Mesh to add to the file - - """ - - warnings.warn("Tallies.add_mesh(...) has been deprecated and may be " - "removed in a future version. Meshes that appear in a " - "tally are automatically added to the collection.", - DeprecationWarning) - - def remove_mesh(self, mesh): - """Remove a mesh from the file - - .. deprecated:: 0.8 - Meshes do not need to be managed explicitly. - - Parameters - ---------- - mesh : openmc.Mesh - Mesh to remove from the file - - """ - warnings.warn("Tallies.remove_mesh(...) has been deprecated and may be " - "removed in a future version. Meshes do not need to be " - "managed explicitly.", DeprecationWarning) - def _create_tally_subelements(self, root_element): for tally in self: root_element.append(tally.to_xml_element()) diff --git a/openmc/trigger.py b/openmc/trigger.py index a5ac1d1e83..c6a0c0b25d 100644 --- a/openmc/trigger.py +++ b/openmc/trigger.py @@ -82,23 +82,6 @@ class Trigger(object): if score not in self._scores: self._scores.append(score) - - def add_score(self, score): - """Add a score to the list of scores to be checked against the trigger. - - Parameters - ---------- - score : str - Score to append - - """ - - warnings.warn('Trigger.add_score(...) has been deprecated and may be ' - 'removed in a future version. Tally trigger scores should ' - 'be defined using the scores property directly.', - DeprecationWarning) - self.scores.append(score) - def get_trigger_xml(self, element): """Return XML representation of the trigger diff --git a/tests/regression_tests/diff_tally/test.py b/tests/regression_tests/diff_tally/test.py index e383b726e8..c106e810fc 100644 --- a/tests/regression_tests/diff_tally/test.py +++ b/tests/regression_tests/diff_tally/test.py @@ -55,30 +55,25 @@ class DiffTallyTestHarness(PyAPITestHarness): # Cover the flux score. for i in range(5): t = openmc.Tally() - t.add_score('flux') - t.add_filter(filt_mats) + t.scores = ['flux'] + t.filters = [filt_mats] t.derivative = derivs[i] self._model.tallies.append(t) # Cover supported scores with a collision estimator. for i in range(5): t = openmc.Tally() - t.add_score('total') - t.add_score('absorption') - t.add_score('scatter') - t.add_score('fission') - t.add_score('nu-fission') - t.add_filter(filt_mats) - t.add_nuclide('total') - t.add_nuclide('U235') + t.scores = ['total', 'absorption', 'scatter', 'fission', 'nu-fission'] + t.filters = [filt_mats] + t.nuclides = ['total', 'U235'] t.derivative = derivs[i] self._model.tallies.append(t) # Cover an analog estimator. for i in range(5): t = openmc.Tally() - t.add_score('absorption') - t.add_filter(filt_mats) + t.scores = ['absorption'] + t.filters = [filt_mats] t.estimator = 'analog' t.derivative = derivs[i] self._model.tallies.append(t) @@ -86,23 +81,18 @@ class DiffTallyTestHarness(PyAPITestHarness): # Energyout filter and total nuclide for the density derivatives. for i in range(2): t = openmc.Tally() - t.add_score('nu-fission') - t.add_score('scatter') - t.add_filter(filt_mats) - t.add_filter(filt_eout) - t.add_nuclide('total') - t.add_nuclide('U235') + t.scores = ['nu-fission', 'scatter'] + t.filters = [filt_mats, filt_eout] + t.nuclides = ['total', 'U235'] t.derivative = derivs[i] self._model.tallies.append(t) # Energyout filter without total nuclide for other derivatives. for i in range(2, 5): t = openmc.Tally() - t.add_score('nu-fission') - t.add_score('scatter') - t.add_filter(filt_mats) - t.add_filter(filt_eout) - t.add_nuclide('U235') + t.scores = ['nu-fission', 'scatter'] + t.filters = [filt_mats, filt_eout] + t.nuclides = ['U235'] t.derivative = derivs[i] self._model.tallies.append(t) From d3d6dc87dcb0323290a835877c91af795652f954 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Feb 2018 10:06:45 -0600 Subject: [PATCH 083/212] Remove a few more __future__ imports. Use collections.abc --- openmc/capi/cell.py | 2 +- openmc/capi/filter.py | 2 +- openmc/capi/material.py | 2 +- openmc/capi/nuclide.py | 2 +- openmc/capi/tally.py | 2 +- openmc/cell.py | 3 ++- openmc/checkvalue.py | 2 +- openmc/cmfd.py | 2 +- openmc/data/angle_distribution.py | 2 +- openmc/data/correlated.py | 2 +- openmc/data/decay.py | 3 ++- openmc/data/endf.py | 3 ++- openmc/data/energy_distribution.py | 2 +- openmc/data/fission_energy.py | 2 +- openmc/data/function.py | 2 +- openmc/data/kalbach_mann.py | 2 +- openmc/data/laboratory.py | 2 +- openmc/data/neutron.py | 3 ++- openmc/data/product.py | 2 +- openmc/data/reaction.py | 2 +- openmc/data/resonance.py | 3 ++- openmc/data/thermal.py | 2 +- openmc/data/urr.py | 2 +- openmc/executor.py | 2 +- openmc/geometry.py | 3 ++- openmc/lattice.py | 3 ++- openmc/mgxs/library.py | 3 ++- openmc/mgxs/mdgxs.py | 3 ++- openmc/model/funcs.py | 3 ++- openmc/model/model.py | 2 +- openmc/model/triso.py | 3 ++- openmc/plots.py | 2 +- openmc/region.py | 3 ++- openmc/search.py | 2 +- openmc/settings.py | 2 +- openmc/stats/multivariate.py | 2 +- openmc/stats/univariate.py | 2 +- openmc/summary.py | 2 +- openmc/tallies.py | 2 +- openmc/trigger.py | 2 +- openmc/volume.py | 3 ++- tests/check_source.py | 4 +--- tests/regression_tests/tally_slice_merge/test.py | 2 -- tests/testing_harness.py | 2 -- 44 files changed, 55 insertions(+), 48 deletions(-) diff --git a/openmc/capi/cell.py b/openmc/capi/cell.py index 0cadfd6af4..3c14aae528 100644 --- a/openmc/capi/cell.py +++ b/openmc/capi/cell.py @@ -1,4 +1,4 @@ -from collections import Mapping, Iterable +from collections.abc import Mapping, Iterable from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index 74c6828d60..ac78c0a341 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER, \ create_string_buffer from weakref import WeakValueDictionary diff --git a/openmc/capi/material.py b/openmc/capi/material.py index af0e9893e4..8a55c27173 100644 --- a/openmc/capi/material.py +++ b/openmc/capi/material.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary diff --git a/openmc/capi/nuclide.py b/openmc/capi/nuclide.py index 54d131498f..f66212c971 100644 --- a/openmc/capi/nuclide.py +++ b/openmc/capi/nuclide.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_char_p, POINTER from weakref import WeakValueDictionary diff --git a/openmc/capi/tally.py b/openmc/capi/tally.py index aaf709e612..f50a19001d 100644 --- a/openmc/capi/tally.py +++ b/openmc/capi/tally.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping from ctypes import c_int, c_int32, c_double, c_char_p, POINTER from weakref import WeakValueDictionary diff --git a/openmc/cell.py b/openmc/cell.py index 838d419b62..c7587e136a 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -1,4 +1,5 @@ -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from math import cos, sin, pi from numbers import Real, Integral diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index 643ea4820f..dd32aa566c 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -1,5 +1,5 @@ import copy -from collections import Iterable +from collections.abc import Iterable import numpy as np diff --git a/openmc/cmfd.py b/openmc/cmfd.py index 236491923d..5444334b20 100644 --- a/openmc/cmfd.py +++ b/openmc/cmfd.py @@ -10,7 +10,7 @@ References """ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from xml.etree import ElementTree as ET import sys diff --git a/openmc/data/angle_distribution.py b/openmc/data/angle_distribution.py index 71e3d2f309..a1f498ba61 100644 --- a/openmc/data/angle_distribution.py +++ b/openmc/data/angle_distribution.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from io import StringIO from numbers import Real from warnings import warn diff --git a/openmc/data/correlated.py b/openmc/data/correlated.py index ba69e6aa6c..8cc4509cea 100644 --- a/openmc/data/correlated.py +++ b/openmc/data/correlated.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from warnings import warn diff --git a/openmc/data/decay.py b/openmc/data/decay.py index 3d365b6c70..d83338d028 100644 --- a/openmc/data/decay.py +++ b/openmc/data/decay.py @@ -1,4 +1,5 @@ -from collections import Iterable, namedtuple +from collections import namedtuple +from collections.abc import Iterable from io import StringIO from math import log from numbers import Real diff --git a/openmc/data/endf.py b/openmc/data/endf.py index 882874b590..160ab61513 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -10,7 +10,8 @@ import io import re import os from math import pi -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable import numpy as np from numpy.polynomial.polynomial import Polynomial diff --git a/openmc/data/energy_distribution.py b/openmc/data/energy_distribution.py index 55588bd648..9e01a4b302 100644 --- a/openmc/data/energy_distribution.py +++ b/openmc/data/energy_distribution.py @@ -1,5 +1,5 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from numbers import Integral, Real from warnings import warn diff --git a/openmc/data/fission_energy.py b/openmc/data/fission_energy.py index a7cf3dfed3..c602ba2c6f 100644 --- a/openmc/data/fission_energy.py +++ b/openmc/data/fission_energy.py @@ -1,4 +1,4 @@ -from collections import Callable +from collections.abc import Callable from copy import deepcopy from io import StringIO import sys diff --git a/openmc/data/function.py b/openmc/data/function.py index 2d3a8ce9c1..3d09e44fc8 100644 --- a/openmc/data/function.py +++ b/openmc/data/function.py @@ -1,5 +1,5 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable, Callable +from collections.abc import Iterable, Callable from numbers import Real, Integral import numpy as np diff --git a/openmc/data/kalbach_mann.py b/openmc/data/kalbach_mann.py index 30a1c01cdc..4be0c15d52 100644 --- a/openmc/data/kalbach_mann.py +++ b/openmc/data/kalbach_mann.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral from warnings import warn diff --git a/openmc/data/laboratory.py b/openmc/data/laboratory.py index 18516d9b87..cfedb292b1 100644 --- a/openmc/data/laboratory.py +++ b/openmc/data/laboratory.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Real, Integral import numpy as np diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index 4f02af1a48..0aa1fe7d83 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -1,5 +1,6 @@ import sys -from collections import OrderedDict, Iterable, Mapping, MutableMapping +from collections import OrderedDict +from collections.abc import Iterable, Mapping, MutableMapping from io import StringIO from itertools import chain from math import log10 diff --git a/openmc/data/product.py b/openmc/data/product.py index b7d89ba0ea..5b8652d771 100644 --- a/openmc/data/product.py +++ b/openmc/data/product.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from io import StringIO from numbers import Real import sys diff --git a/openmc/data/reaction.py b/openmc/data/reaction.py index 737885f357..d3df038f55 100644 --- a/openmc/data/reaction.py +++ b/openmc/data/reaction.py @@ -1,4 +1,4 @@ -from collections import Iterable, Callable, MutableMapping +from collections.abc import Iterable, Callable, MutableMapping from copy import deepcopy from numbers import Real, Integral from warnings import warn diff --git a/openmc/data/resonance.py b/openmc/data/resonance.py index 5e7e0c44d7..d58f706eb9 100644 --- a/openmc/data/resonance.py +++ b/openmc/data/resonance.py @@ -1,4 +1,5 @@ -from collections import defaultdict, MutableSequence, Iterable +from collections import defaultdict +from collections.abc import MutableSequence, Iterable import io import numpy as np diff --git a/openmc/data/thermal.py b/openmc/data/thermal.py index 4f89d8e834..a036a2680c 100644 --- a/openmc/data/thermal.py +++ b/openmc/data/thermal.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from difflib import get_close_matches from numbers import Real import itertools diff --git a/openmc/data/urr.py b/openmc/data/urr.py index 1f915974b1..0edccf6f06 100644 --- a/openmc/data/urr.py +++ b/openmc/data/urr.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable from numbers import Integral, Real import numpy as np diff --git a/openmc/executor.py b/openmc/executor.py index e3768f4c61..8ad2bd8960 100644 --- a/openmc/executor.py +++ b/openmc/executor.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable import subprocess from numbers import Integral diff --git a/openmc/geometry.py b/openmc/geometry.py index 7e14272698..1ee93dfd6d 100644 --- a/openmc/geometry.py +++ b/openmc/geometry.py @@ -1,4 +1,5 @@ -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from xml.etree import ElementTree as ET diff --git a/openmc/lattice.py b/openmc/lattice.py index 0819a85917..2f7fcf56df 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -1,5 +1,6 @@ from abc import ABCMeta -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from copy import deepcopy from math import sqrt, floor from numbers import Real, Integral diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index c8b151e024..9add7004bb 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -3,7 +3,8 @@ import os import copy import pickle from numbers import Integral -from collections import OrderedDict, Iterable +from collections import OrderedDict +from collections.abc import Iterable from warnings import warn import numpy as np diff --git a/openmc/mgxs/mdgxs.py b/openmc/mgxs/mdgxs.py index dfd0d192d9..2d278d62d7 100644 --- a/openmc/mgxs/mdgxs.py +++ b/openmc/mgxs/mdgxs.py @@ -1,4 +1,5 @@ -from collections import Iterable, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable import itertools from numbers import Integral import warnings diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index b5afdf08d1..6013f6caee 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -1,4 +1,5 @@ -from collections import Iterable, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable from math import sqrt from numbers import Real diff --git a/openmc/model/model.py b/openmc/model/model.py index 17de6fc2e6..89fa84e604 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable import openmc from openmc.checkvalue import check_type diff --git a/openmc/model/triso.py b/openmc/model/triso.py index fab2f54cc1..2786216f77 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -2,7 +2,8 @@ import copy import warnings import itertools import random -from collections import Iterable, defaultdict +from collections import defaultdict +from collections.abc import Iterable from numbers import Real from random import uniform, gauss from heapq import heappush, heappop diff --git a/openmc/plots.py b/openmc/plots.py index 159e920780..4414a39e13 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -1,4 +1,4 @@ -from collections import Iterable, Mapping +from collections.abc import Iterable, Mapping from numbers import Real, Integral from xml.etree import ElementTree as ET import sys diff --git a/openmc/region.py b/openmc/region.py index c9bd3b5fc0..f82db8553b 100644 --- a/openmc/region.py +++ b/openmc/region.py @@ -1,5 +1,6 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable, OrderedDict, MutableSequence +from collections import OrderedDict +from collections.abc import Iterable, MutableSequence from copy import deepcopy import numpy as np diff --git a/openmc/search.py b/openmc/search.py index 7f91438fd7..75935097e4 100644 --- a/openmc/search.py +++ b/openmc/search.py @@ -1,4 +1,4 @@ -from collections import Callable +from collections.abc import Callable from numbers import Real import scipy.optimize as sopt diff --git a/openmc/settings.py b/openmc/settings.py index b9562b7ddc..62cfc27aaa 100644 --- a/openmc/settings.py +++ b/openmc/settings.py @@ -1,4 +1,4 @@ -from collections import Iterable, MutableSequence, Mapping +from collections.abc import Iterable, MutableSequence, Mapping from numbers import Real, Integral import warnings from xml.etree import ElementTree as ET diff --git a/openmc/stats/multivariate.py b/openmc/stats/multivariate.py index 1fe883866f..ac788c3443 100644 --- a/openmc/stats/multivariate.py +++ b/openmc/stats/multivariate.py @@ -1,5 +1,5 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from math import pi from numbers import Real import sys diff --git a/openmc/stats/univariate.py b/openmc/stats/univariate.py index 6996970af1..16a9dbb9e7 100644 --- a/openmc/stats/univariate.py +++ b/openmc/stats/univariate.py @@ -1,5 +1,5 @@ from abc import ABCMeta, abstractmethod -from collections import Iterable +from collections.abc import Iterable from numbers import Real import sys from xml.etree import ElementTree as ET diff --git a/openmc/summary.py b/openmc/summary.py index 34743757b4..aa98025c08 100644 --- a/openmc/summary.py +++ b/openmc/summary.py @@ -1,4 +1,4 @@ -from collections import Iterable +from collections.abc import Iterable import re import warnings diff --git a/openmc/tallies.py b/openmc/tallies.py index 61be38fb2a..d22cfdcb46 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1,4 +1,4 @@ -from collections import Iterable, MutableSequence +from collections.abc import Iterable, MutableSequence import copy import re from functools import partial, reduce diff --git a/openmc/trigger.py b/openmc/trigger.py index c6a0c0b25d..71f9c0b92b 100644 --- a/openmc/trigger.py +++ b/openmc/trigger.py @@ -2,7 +2,7 @@ from numbers import Real from xml.etree import ElementTree as ET import sys import warnings -from collections import Iterable +from collections.abc import Iterable import openmc.checkvalue as cv diff --git a/openmc/volume.py b/openmc/volume.py index cccb3c6a27..d61093a178 100644 --- a/openmc/volume.py +++ b/openmc/volume.py @@ -1,4 +1,5 @@ -from collections import Iterable, Mapping, OrderedDict +from collections import OrderedDict +from collections.abc import Iterable, Mapping from numbers import Real, Integral from xml.etree import ElementTree as ET import warnings diff --git a/tests/check_source.py b/tests/check_source.py index 3a79d44c28..78cef2a0cd 100755 --- a/tests/check_source.py +++ b/tests/check_source.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python - -from __future__ import print_function +#!/usr/bin/env python3 import glob from string import whitespace diff --git a/tests/regression_tests/tally_slice_merge/test.py b/tests/regression_tests/tally_slice_merge/test.py index c198411f7d..ff35c177f5 100644 --- a/tests/regression_tests/tally_slice_merge/test.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -1,5 +1,3 @@ -from __future__ import division - import hashlib import itertools diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 55a5660f1c..6c9e25b457 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -1,5 +1,3 @@ -from __future__ import print_function - from difflib import unified_diff import filecmp import glob From 19ddb532bc3ae5a801e4a689010799b762539fcc Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 06:53:43 -0500 Subject: [PATCH 084/212] Remove check for Python 2.7 in travis-install --- tools/ci/travis-install.sh | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 58bcfb789d..3efadd6f36 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -10,11 +10,6 @@ pip install numpy cython # pytest installed by default -- make sure we get latest pip install --upgrade pytest -# IPython stopped supporting Python 2.7 with version 6 -if [[ "$TRAVIS_PYTHON_VERSION" == "2.7" ]]; then - pip install "ipython<6" -fi - # Pandas stopped supporting Python 3.4 with version 0.21 if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then pip install pandas==0.20.3 From b053e054156cfbd314e515db2b1bdab53263575c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 07:25:21 -0500 Subject: [PATCH 085/212] Remove try/except for importing unittest.mock --- docs/source/conf.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index b97ff782d9..db44e34f4d 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -18,10 +18,7 @@ on_rtd = os.environ.get('READTHEDOCS', None) == 'True' # On Read the Docs, we need to mock a few third-party modules so we don't get # ImportErrors when building documentation -try: - from unittest.mock import MagicMock -except ImportError: - from mock import Mock as MagicMock +from unittest.mock import MagicMock MOCK_MODULES = ['numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial', @@ -254,6 +251,6 @@ napoleon_use_ivar = True intersphinx_mapping = { 'python': ('https://docs.python.org/3', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None), - 'pandas': ('http://pandas.pydata.org/pandas-docs/stable/', None), + 'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None), 'matplotlib': ('https://matplotlib.org/', None) } From cba083103c27df2924efc5a9c70073b0963d1d0d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 07:29:39 -0500 Subject: [PATCH 086/212] Use default argument of max() in capi bindings --- openmc/capi/cell.py | 5 +---- openmc/capi/filter.py | 5 +---- openmc/capi/material.py | 5 +---- openmc/capi/tally.py | 5 +---- 4 files changed, 4 insertions(+), 16 deletions(-) diff --git a/openmc/capi/cell.py b/openmc/capi/cell.py index 3c14aae528..0ab3f2583e 100644 --- a/openmc/capi/cell.py +++ b/openmc/capi/cell.py @@ -65,10 +65,7 @@ class Cell(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A cell with ID={} has already ' diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index ac78c0a341..79c19a6248 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -66,10 +66,7 @@ class Filter(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A filter with ID={} has already ' diff --git a/openmc/capi/material.py b/openmc/capi/material.py index 8a55c27173..62d6df012a 100644 --- a/openmc/capi/material.py +++ b/openmc/capi/material.py @@ -78,10 +78,7 @@ class Material(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A material with ID={} has already ' diff --git a/openmc/capi/tally.py b/openmc/capi/tally.py index f50a19001d..a78347177d 100644 --- a/openmc/capi/tally.py +++ b/openmc/capi/tally.py @@ -155,10 +155,7 @@ class Tally(_FortranObjectWithID): if new: # Determine ID to assign if uid is None: - try: - uid = max(mapping) + 1 - except ValueError: - uid = 1 + uid = max(mapping, default=0) + 1 else: if uid in mapping: raise AllocationError('A tally with ID={} has already ' From 59861c9507142d0d2f2120c96cbcec19f82b9cf8 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 07:35:45 -0500 Subject: [PATCH 087/212] No need to call int(floor(...)) in Python 3 --- openmc/lattice.py | 12 ++++++------ openmc/model/triso.py | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/openmc/lattice.py b/openmc/lattice.py index 2f7fcf56df..86cfd5c41b 100644 --- a/openmc/lattice.py +++ b/openmc/lattice.py @@ -604,12 +604,12 @@ class RectLattice(Lattice): element coordinate system """ - ix = int(floor((point[0] - self.lower_left[0])/self.pitch[0])) - iy = int(floor((point[1] - self.lower_left[1])/self.pitch[1])) + ix = floor((point[0] - self.lower_left[0])/self.pitch[0]) + iy = floor((point[1] - self.lower_left[1])/self.pitch[1]) if self.ndim == 2: idx = (ix, iy) else: - iz = int(floor((point[2] - self.lower_left[2])/self.pitch[2])) + iz = floor((point[2] - self.lower_left[2])/self.pitch[2]) idx = (ix, iy, iz) return idx, self.get_local_coordinates(point, idx) @@ -1016,10 +1016,10 @@ class HexLattice(Lattice): iz = 1 else: z = point[2] - self.center[2] - iz = int(floor(z/self.pitch[1] + 0.5*self.num_axial)) + iz = floor(z/self.pitch[1] + 0.5*self.num_axial) alpha = y - x/sqrt(3.) - ix = int(floor(x/(sqrt(0.75) * self.pitch[0]))) - ia = int(floor(alpha/self.pitch[0])) + ix = floor(x/(sqrt(0.75) * self.pitch[0])) + ia = floor(alpha/self.pitch[0]) # Check four lattice elements to see which one is closest based on local # coordinates diff --git a/openmc/model/triso.py b/openmc/model/triso.py index 2786216f77..5fe51b6644 100644 --- a/openmc/model/triso.py +++ b/openmc/model/triso.py @@ -736,7 +736,7 @@ def _close_random_pack(domain, particles, contraction_rate): outer_pf = (4/3 * pi * (outer_diameter[0]/2)**3 * n_particles / domain.volume) - j = int(floor(-log10(outer_pf - inner_pf))) + j = floor(-log10(outer_pf - inner_pf)) outer_diameter[0] = (outer_diameter[0] - 0.5**j * contraction_rate * initial_outer_diameter / n_particles) From b7c63be018c765092377a463b3fd25cc559d8d92 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 13:14:17 -0500 Subject: [PATCH 088/212] Use super() in Python classes in tests package --- tests/regression_tests/asymmetric_lattice/test.py | 2 +- tests/regression_tests/diff_tally/test.py | 2 +- tests/regression_tests/distribmat/test.py | 2 +- tests/regression_tests/filter_distribcell/test.py | 2 +- tests/regression_tests/filter_energyfun/test.py | 2 +- tests/regression_tests/filter_mesh/test.py | 2 +- tests/regression_tests/mg_convert/test.py | 2 +- tests/regression_tests/mgxs_library_ce_to_mg/test.py | 4 ++-- tests/regression_tests/mgxs_library_condense/test.py | 2 +- .../regression_tests/mgxs_library_distribcell/test.py | 2 +- tests/regression_tests/mgxs_library_hdf5/test.py | 4 ++-- tests/regression_tests/mgxs_library_mesh/test.py | 2 +- .../regression_tests/mgxs_library_no_nuclides/test.py | 2 +- tests/regression_tests/mgxs_library_nuclides/test.py | 2 +- tests/regression_tests/multipole/test.py | 4 ++-- tests/regression_tests/plot/test.py | 4 ++-- tests/regression_tests/statepoint_batch/test.py | 2 +- tests/regression_tests/statepoint_restart/test.py | 2 +- tests/regression_tests/tally_aggregation/test.py | 2 +- tests/regression_tests/tally_arithmetic/test.py | 2 +- tests/regression_tests/tally_slice_merge/test.py | 2 +- tests/testing_harness.py | 10 +++++----- 22 files changed, 30 insertions(+), 30 deletions(-) diff --git a/tests/regression_tests/asymmetric_lattice/test.py b/tests/regression_tests/asymmetric_lattice/test.py index 0318d7b922..d6a0ab9b73 100644 --- a/tests/regression_tests/asymmetric_lattice/test.py +++ b/tests/regression_tests/asymmetric_lattice/test.py @@ -9,7 +9,7 @@ from tests.testing_harness import PyAPITestHarness class AsymmetricLatticeTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(AsymmetricLatticeTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Extract universes encapsulating fuel and water assemblies geometry = self._model.geometry diff --git a/tests/regression_tests/diff_tally/test.py b/tests/regression_tests/diff_tally/test.py index c106e810fc..bd6792414b 100644 --- a/tests/regression_tests/diff_tally/test.py +++ b/tests/regression_tests/diff_tally/test.py @@ -9,7 +9,7 @@ from tests.testing_harness import PyAPITestHarness class DiffTallyTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(DiffTallyTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Set settings explicitly self._model.settings.batches = 3 diff --git a/tests/regression_tests/distribmat/test.py b/tests/regression_tests/distribmat/test.py index 69bb7a67b1..de1b778772 100644 --- a/tests/regression_tests/distribmat/test.py +++ b/tests/regression_tests/distribmat/test.py @@ -93,7 +93,7 @@ class DistribmatTestHarness(PyAPITestHarness): plots.export_to_xml() def _get_results(self): - outstr = super(DistribmatTestHarness, self)._get_results() + outstr = super()._get_results() su = openmc.Summary('summary.h5') outstr += str(su.geometry.get_all_cells()[11]) return outstr diff --git a/tests/regression_tests/filter_distribcell/test.py b/tests/regression_tests/filter_distribcell/test.py index bdd134bf57..028c6a7790 100644 --- a/tests/regression_tests/filter_distribcell/test.py +++ b/tests/regression_tests/filter_distribcell/test.py @@ -6,7 +6,7 @@ from tests.testing_harness import * class DistribcellTestHarness(TestHarness): def __init__(self): - super(DistribcellTestHarness, self).__init__(None) + super().__init__(None) def execute_test(self): """Run OpenMC with the appropriate arguments and check the outputs.""" diff --git a/tests/regression_tests/filter_energyfun/test.py b/tests/regression_tests/filter_energyfun/test.py index d9148dd35d..7c5645b651 100644 --- a/tests/regression_tests/filter_energyfun/test.py +++ b/tests/regression_tests/filter_energyfun/test.py @@ -5,7 +5,7 @@ from tests.testing_harness import PyAPITestHarness class FilterEnergyFunHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(FilterEnergyFunHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Add Am241 to the fuel. self._model.materials[1].add_nuclide('Am241', 1e-7) diff --git a/tests/regression_tests/filter_mesh/test.py b/tests/regression_tests/filter_mesh/test.py index 66cd1ac19f..e0c6dd0f2f 100644 --- a/tests/regression_tests/filter_mesh/test.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -5,7 +5,7 @@ from tests.testing_harness import HashedPyAPITestHarness class FilterMeshTestHarness(HashedPyAPITestHarness): def __init__(self, *args, **kwargs): - super(FilterMeshTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize Meshes mesh_1d = openmc.Mesh(mesh_id=1) diff --git a/tests/regression_tests/mg_convert/test.py b/tests/regression_tests/mg_convert/test.py index 4bbbcbeb9a..5b816a1cd0 100755 --- a/tests/regression_tests/mg_convert/test.py +++ b/tests/regression_tests/mg_convert/test.py @@ -159,7 +159,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() + super()._cleanup() f = os.path.join(os.getcwd(), 'mgxs.h5') if os.path.exists(f): os.remove(f) diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/test.py b/tests/regression_tests/mgxs_library_ce_to_mg/test.py index 922b2c302c..72f052e68e 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/test.py +++ b/tests/regression_tests/mgxs_library_ce_to_mg/test.py @@ -11,7 +11,7 @@ from tests.regression_tests import config class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -71,7 +71,7 @@ class MGXSTestHarness(PyAPITestHarness): openmc.run(openmc_exec=config['exe']) def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() + super()._cleanup() f = 'mgxs.h5' if os.path.exists(f): os.remove(f) diff --git a/tests/regression_tests/mgxs_library_condense/test.py b/tests/regression_tests/mgxs_library_condense/test.py index 06b4704784..167772e2fd 100644 --- a/tests/regression_tests/mgxs_library_condense/test.py +++ b/tests/regression_tests/mgxs_library_condense/test.py @@ -9,7 +9,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) diff --git a/tests/regression_tests/mgxs_library_distribcell/test.py b/tests/regression_tests/mgxs_library_distribcell/test.py index d7bc84bf57..5290d313bb 100644 --- a/tests/regression_tests/mgxs_library_distribcell/test.py +++ b/tests/regression_tests/mgxs_library_distribcell/test.py @@ -10,7 +10,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a one-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 20.e6]) diff --git a/tests/regression_tests/mgxs_library_hdf5/test.py b/tests/regression_tests/mgxs_library_hdf5/test.py index 8eed0258aa..9811ab2155 100644 --- a/tests/regression_tests/mgxs_library_hdf5/test.py +++ b/tests/regression_tests/mgxs_library_hdf5/test.py @@ -13,7 +13,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) @@ -67,7 +67,7 @@ class MGXSTestHarness(PyAPITestHarness): return outstr def _cleanup(self): - super(MGXSTestHarness, self)._cleanup() + super()._cleanup() f = 'mgxs.h5' if os.path.exists(f): os.remove(f) diff --git a/tests/regression_tests/mgxs_library_mesh/test.py b/tests/regression_tests/mgxs_library_mesh/test.py index 70bd2113ce..a9d24da934 100644 --- a/tests/regression_tests/mgxs_library_mesh/test.py +++ b/tests/regression_tests/mgxs_library_mesh/test.py @@ -8,7 +8,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a one-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 20.e6]) diff --git a/tests/regression_tests/mgxs_library_no_nuclides/test.py b/tests/regression_tests/mgxs_library_no_nuclides/test.py index c59b52189e..506ac238fc 100644 --- a/tests/regression_tests/mgxs_library_no_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_no_nuclides/test.py @@ -10,7 +10,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): # Generate inputs using parent class routine - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) diff --git a/tests/regression_tests/mgxs_library_nuclides/test.py b/tests/regression_tests/mgxs_library_nuclides/test.py index a65fb9a6d3..c64c277098 100644 --- a/tests/regression_tests/mgxs_library_nuclides/test.py +++ b/tests/regression_tests/mgxs_library_nuclides/test.py @@ -9,7 +9,7 @@ from tests.testing_harness import PyAPITestHarness class MGXSTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(MGXSTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize a two-group structure energy_groups = openmc.mgxs.EnergyGroups(group_edges=[0, 0.625, 20.e6]) diff --git a/tests/regression_tests/multipole/test.py b/tests/regression_tests/multipole/test.py index 43aa9963aa..82e6bb4cd7 100644 --- a/tests/regression_tests/multipole/test.py +++ b/tests/regression_tests/multipole/test.py @@ -71,10 +71,10 @@ class MultipoleTestHarness(PyAPITestHarness): raise RuntimeError("The 'OPENMC_MULTIPOLE_LIBRARY' environment " "variable must be specified for this test.") else: - super(MultipoleTestHarness, self).execute_test() + super().execute_test() def _get_results(self): - outstr = super(MultipoleTestHarness, self)._get_results() + outstr = super()._get_results() su = openmc.Summary('summary.h5') outstr += str(su.geometry.get_all_cells()[11]) return outstr diff --git a/tests/regression_tests/plot/test.py b/tests/regression_tests/plot/test.py index e7115c4dde..bfaef019c1 100644 --- a/tests/regression_tests/plot/test.py +++ b/tests/regression_tests/plot/test.py @@ -12,7 +12,7 @@ from tests.regression_tests import config class PlotTestHarness(TestHarness): """Specialized TestHarness for running OpenMC plotting tests.""" def __init__(self, plot_names): - super(PlotTestHarness, self).__init__(None) + super().__init__(None) self._plot_names = plot_names def _run_openmc(self): @@ -24,7 +24,7 @@ class PlotTestHarness(TestHarness): assert os.path.exists(fname), 'Plot output file does not exist.' def _cleanup(self): - super(PlotTestHarness, self)._cleanup() + super()._cleanup() for fname in self._plot_names: if os.path.exists(fname): os.remove(fname) diff --git a/tests/regression_tests/statepoint_batch/test.py b/tests/regression_tests/statepoint_batch/test.py index 6c5e4de318..323b28fc65 100644 --- a/tests/regression_tests/statepoint_batch/test.py +++ b/tests/regression_tests/statepoint_batch/test.py @@ -3,7 +3,7 @@ from tests.testing_harness import TestHarness class StatepointTestHarness(TestHarness): def __init__(self): - super(StatepointTestHarness, self).__init__(None) + super().__init__(None) def _test_output_created(self): """Make sure statepoint files have been created.""" diff --git a/tests/regression_tests/statepoint_restart/test.py b/tests/regression_tests/statepoint_restart/test.py index d36ff93950..4575607f7d 100644 --- a/tests/regression_tests/statepoint_restart/test.py +++ b/tests/regression_tests/statepoint_restart/test.py @@ -9,7 +9,7 @@ from tests.regression_tests import config class StatepointRestartTestHarness(TestHarness): def __init__(self, final_sp, restart_sp): - super(StatepointRestartTestHarness, self).__init__(final_sp) + super().__init__(final_sp) self._restart_sp = restart_sp def execute_test(self): diff --git a/tests/regression_tests/tally_aggregation/test.py b/tests/regression_tests/tally_aggregation/test.py index f723160737..f7df543ded 100644 --- a/tests/regression_tests/tally_aggregation/test.py +++ b/tests/regression_tests/tally_aggregation/test.py @@ -7,7 +7,7 @@ from tests.testing_harness import PyAPITestHarness class TallyAggregationTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallyAggregationTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize the filters energy_filter = openmc.EnergyFilter([0.0, 0.253, 1.0e3, 1.0e6, 20.0e6]) diff --git a/tests/regression_tests/tally_arithmetic/test.py b/tests/regression_tests/tally_arithmetic/test.py index 469ed00de1..3adf0c5bef 100644 --- a/tests/regression_tests/tally_arithmetic/test.py +++ b/tests/regression_tests/tally_arithmetic/test.py @@ -7,7 +7,7 @@ from tests.testing_harness import PyAPITestHarness class TallyArithmeticTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallyArithmeticTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Initialize Mesh mesh = openmc.Mesh(mesh_id=1) diff --git a/tests/regression_tests/tally_slice_merge/test.py b/tests/regression_tests/tally_slice_merge/test.py index ff35c177f5..f79c8b2685 100644 --- a/tests/regression_tests/tally_slice_merge/test.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -8,7 +8,7 @@ from tests.testing_harness import PyAPITestHarness class TallySliceMergeTestHarness(PyAPITestHarness): def __init__(self, *args, **kwargs): - super(TallySliceMergeTestHarness, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Define nuclides and scores to add to both tallies self.nuclides = ['U235', 'U238'] diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 6c9e25b457..92d477e238 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -127,7 +127,7 @@ class HashedTestHarness(TestHarness): def _get_results(self): """Digest info in the statepoint and return as a string.""" - return super(HashedTestHarness, self)._get_results(True) + return super()._get_results(True) class CMFDTestHarness(TestHarness): @@ -137,7 +137,7 @@ class CMFDTestHarness(TestHarness): """Digest info in the statepoint and return as a string.""" # Write out the eigenvalue and tallies. - outstr = super(CMFDTestHarness, self)._get_results() + outstr = super()._get_results() # Read the statepoint file. statepoint = glob.glob(self._sp_name)[0] @@ -220,7 +220,7 @@ class ParticleRestartTestHarness(TestHarness): class PyAPITestHarness(TestHarness): def __init__(self, statepoint_name, model=None): - super(PyAPITestHarness, self).__init__(statepoint_name) + super().__init__(statepoint_name) if model is None: self._model = pwr_core() else: @@ -300,7 +300,7 @@ class PyAPITestHarness(TestHarness): def _cleanup(self): """Delete XMLs, statepoints, tally, and test files.""" - super(PyAPITestHarness, self)._cleanup() + super()._cleanup() output = ['materials.xml', 'geometry.xml', 'settings.xml', 'tallies.xml', 'plots.xml', 'inputs_test.dat'] for f in output: @@ -311,4 +311,4 @@ class PyAPITestHarness(TestHarness): class HashedPyAPITestHarness(PyAPITestHarness): def _get_results(self): """Digest info in the statepoint and return as a string.""" - return super(HashedPyAPITestHarness, self)._get_results(True) + return super()._get_results(True) From 848305b8d38ceb490655f049a7b49f618484a666 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 6 Feb 2018 13:27:01 -0500 Subject: [PATCH 089/212] Skip multipole-related tests if OPENMC_MULTIPOLE_LIBRARY is not set --- pytest.ini | 1 + tests/regression_tests/diff_tally/test.py | 4 ++++ tests/regression_tests/multipole/test.py | 11 ++++------- tests/unit_tests/test_data_multipole.py | 7 +++++-- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/pytest.ini b/pytest.ini index d960ba8d25..cdd367ea9d 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,3 +2,4 @@ python_files = test*.py python_classes = NoThanks filterwarnings = ignore::UserWarning +addopts = -rs diff --git a/tests/regression_tests/diff_tally/test.py b/tests/regression_tests/diff_tally/test.py index bd6792414b..de5423fd9f 100644 --- a/tests/regression_tests/diff_tally/test.py +++ b/tests/regression_tests/diff_tally/test.py @@ -3,6 +3,7 @@ import os import pandas as pd import openmc +import pytest from tests.testing_harness import PyAPITestHarness @@ -112,6 +113,9 @@ class DiffTallyTestHarness(PyAPITestHarness): return df.to_csv(None, columns=cols, index=False, float_format='%.7e') +@pytest.mark.skipif('OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable ' + 'must be set') def test_diff_tally(): harness = DiffTallyTestHarness('statepoint.3.h5') harness.main() diff --git a/tests/regression_tests/multipole/test.py b/tests/regression_tests/multipole/test.py index 82e6bb4cd7..5c79d4d6b6 100644 --- a/tests/regression_tests/multipole/test.py +++ b/tests/regression_tests/multipole/test.py @@ -2,6 +2,7 @@ import os import openmc import openmc.model +import pytest from tests.testing_harness import TestHarness, PyAPITestHarness @@ -66,13 +67,6 @@ def make_model(): class MultipoleTestHarness(PyAPITestHarness): - def execute_test(self): - if not 'OPENMC_MULTIPOLE_LIBRARY' in os.environ: - raise RuntimeError("The 'OPENMC_MULTIPOLE_LIBRARY' environment " - "variable must be specified for this test.") - else: - super().execute_test() - def _get_results(self): outstr = super()._get_results() su = openmc.Summary('summary.h5') @@ -80,6 +74,9 @@ class MultipoleTestHarness(PyAPITestHarness): return outstr +@pytest.mark.skipif('OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable ' + 'must be set') def test_multipole(): model = make_model() harness = MultipoleTestHarness('statepoint.5.h5', model) diff --git a/tests/unit_tests/test_data_multipole.py b/tests/unit_tests/test_data_multipole.py index dc30677e80..4a4a9f0d21 100644 --- a/tests/unit_tests/test_data_multipole.py +++ b/tests/unit_tests/test_data_multipole.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - import os import numpy as np @@ -7,6 +5,11 @@ import pytest import openmc.data +pytestmark = pytest.mark.skipif( + 'OPENMC_MULTIPOLE_LIBRARY' not in os.environ, + reason='OPENMC_MULTIPOLE_LIBRARY environment variable must be set') + + @pytest.fixture(scope='module') def u235(): directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] From ddc60ec6f0521b5d67f8a5bc99205118efb61038 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Tue, 6 Feb 2018 19:27:39 -0500 Subject: [PATCH 090/212] Inelastic scattering index list --- src/nuclide_header.F90 | 18 ++++++++++++++++++ src/physics.F90 | 22 ++++++---------------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index fd2577508a..8bbf103e3e 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -100,6 +100,7 @@ module nuclide_header ! Reactions type(Reaction), allocatable :: reactions(:) + integer, allocatable :: index_inelastic_scatter(:) ! Array that maps MT values to index in reactions; used at tally-time. Note ! that ENDF-102 does not assign any MT values above 891. @@ -302,6 +303,7 @@ contains real(8) :: temp_actual type(VectorInt) :: MTs type(VectorInt) :: temps_to_read + type(VectorInt) :: index_inelastic_scatter_vector ! Get name of nuclide from group name_len = len(this % name) @@ -469,10 +471,26 @@ contains end if end if + ! Add the reaction index to the scattering array if this is an inelastic + ! scatter reaction + if (MTs % data(i) /= N_FISSION .and. MTs % data(i) /= N_F .and. & + MTs % data(i) /= N_NF .and. MTs % data(i) /= N_2NF .and. & + MTs % data(i) /= N_3NF .and. MTs % data(i) < 200 .and. & + MTs % data(i) /= N_LEVEL .and. MTs % data(i) /= ELASTIC) then + + call index_inelastic_scatter_vector % push_back(i) + end if + call close_group(rx_group) end do call close_group(rxs_group) + ! Recast to a regular array to save space + allocate(this % index_inelastic_scatter( & + index_inelastic_scatter_vector % size())) + this % index_inelastic_scatter = index_inelastic_scatter_vector % data(:) + call index_inelastic_scatter_vector % clear() + ! Read unresolved resonance probability tables if present if (object_exists(group_id, 'urr')) then this % urr_present = .true. diff --git a/src/physics.F90 b/src/physics.F90 index 98fef8b921..721e3dd6c1 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -310,6 +310,7 @@ contains integer, intent(in) :: i_nuc_mat integer :: i + integer :: j integer :: i_temp integer :: i_grid real(8) :: f @@ -378,11 +379,10 @@ contains ! ======================================================================= ! INELASTIC SCATTERING - ! note that indexing starts from 2 since nuc % reactions(1) is elastic - ! scattering - i = 1 + j = 0 do while (prob < cutoff) - i = i + 1 + j = j + 1 + i = nuc % index_inelastic_scatter(j) ! Check to make sure inelastic scattering reaction sampled if (i > size(nuc % reactions)) then @@ -391,24 +391,14 @@ contains &// trim(nuc % name)) end if - associate (rx => nuc % reactions(i)) - ! Skip fission reactions - if (rx % MT == N_FISSION .or. rx % MT == N_F .or. rx % MT == N_NF & - .or. rx % MT == N_2NF .or. rx % MT == N_3NF) cycle - - ! Some materials have gas production cross sections with MT > 200 that - ! are duplicates. Also MT=4 is total level inelastic scattering which - ! should be skipped - if (rx % MT >= 200 .or. rx % MT == N_LEVEL) cycle - - associate (xs => rx % xs(i_temp)) + associate (rx => nuc % reactions(i), & + xs => nuc % reactions(i) % xs(i_temp)) ! if energy is below threshold for this reaction, skip it if (i_grid < xs % threshold) cycle ! add to cumulative probability prob = prob + ((ONE - f)*xs % value(i_grid - xs % threshold + 1) & + f*(xs % value(i_grid - xs % threshold + 2))) - end associate end associate end do From 7d4cc0094eb2dc885710d3691e4f52c3fd1e50a8 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Tue, 6 Feb 2018 19:33:58 -0500 Subject: [PATCH 091/212] Fixing further misidentations --- src/nuclide_header.F90 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index 8bbf103e3e..c0c5c2627d 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -474,9 +474,9 @@ contains ! Add the reaction index to the scattering array if this is an inelastic ! scatter reaction if (MTs % data(i) /= N_FISSION .and. MTs % data(i) /= N_F .and. & - MTs % data(i) /= N_NF .and. MTs % data(i) /= N_2NF .and. & - MTs % data(i) /= N_3NF .and. MTs % data(i) < 200 .and. & - MTs % data(i) /= N_LEVEL .and. MTs % data(i) /= ELASTIC) then + MTs % data(i) /= N_NF .and. MTs % data(i) /= N_2NF .and. & + MTs % data(i) /= N_3NF .and. MTs % data(i) < 200 .and. & + MTs % data(i) /= N_LEVEL .and. MTs % data(i) /= ELASTIC) then call index_inelastic_scatter_vector % push_back(i) end if From dacf650eaf74ce6b138c0225cfcc83d4c622a39d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 8 Feb 2018 14:32:28 -0600 Subject: [PATCH 092/212] Fix bug with clearing k_generation and entropy --- src/simulation.F90 | 2 ++ tests/__init__.py | 15 +++++++++++++++ tests/unit_tests/test_capi.py | 33 ++++++++++++++++++++------------- 3 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/simulation.F90 b/src/simulation.F90 index 424c55e9bd..0204aaf796 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -454,6 +454,8 @@ contains ! Reset global variables current_batch = 0 + call k_generation % clear() + call entropy % clear() need_depletion_rx = .false. ! Set flag indicating initialization is done diff --git a/tests/__init__.py b/tests/__init__.py index e69de29bb2..5c21cd9380 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +from contextlib import contextmanager +import os +import tempfile + + +@contextmanager +def cdtemp(): + """Context manager to change to/return from a tmpdir.""" + with tempfile.TemporaryDirectory() as tmpdir: + cwd = os.getcwd() + try: + os.chdir(tmpdir) + yield + finally: + os.chdir(cwd) diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index e1e87e27b3..618f54e4f9 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - from collections import Mapping import os @@ -8,12 +6,15 @@ import pytest import openmc import openmc.capi +from tests import cdtemp + @pytest.fixture(scope='module') def pincell_model(): """Set up a model to test with and delete files when done""" openmc.reset_auto_ids() pincell = openmc.examples.pwr_pin_cell() + pincell.settings.verbosity = 1 # Add a tally filter1 = openmc.MaterialFilter(pincell.materials) @@ -24,17 +25,10 @@ def pincell_model(): mat_tally.scores = ['total', 'elastic', '(n,gamma)'] pincell.tallies.append(mat_tally) - # Write XML files - pincell.export_to_xml() - - yield - - # Delete generated files - files = ['geometry.xml', 'materials.xml', 'settings.xml', 'tallies.xml', - 'statepoint.10.h5', 'summary.h5', 'test_sp.h5'] - for f in files: - if os.path.exists(f): - os.remove(f) + # Write XML files in tmpdir + with cdtemp(): + pincell.export_to_xml() + yield @pytest.fixture(scope='module') @@ -229,6 +223,19 @@ def test_by_batch(capi_run): openmc.capi.simulation_finalize() +def test_reproduce_keff(capi_init): + # Get k-effective after run + openmc.capi.hard_reset() + openmc.capi.run() + keff0 = openmc.capi.keff() + + # Reset, run again, and get k-effective again. they should match + openmc.capi.hard_reset() + openmc.capi.run() + keff1 = openmc.capi.keff() + assert keff0 == pytest.approx(keff1) + + def test_find_cell(capi_init): cell, instance = openmc.capi.find_cell((0., 0., 0.)) assert cell is openmc.capi.cells[1] From 899b6b67996489ae6e3369156ce7017e902031a1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 8 Feb 2018 15:34:39 -0600 Subject: [PATCH 093/212] Make sure k_generation and entropy are cleared before loading state point --- src/simulation.F90 | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/simulation.F90 b/src/simulation.F90 index 0204aaf796..34c4336944 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -434,6 +434,13 @@ contains allocate(filter_matches(n_filters)) !$omp end parallel + ! Reset global variables -- this is done before loading state point (as that + ! will potentially populate k_generation and entropy) + current_batch = 0 + call k_generation % clear() + call entropy % clear() + need_depletion_rx = .false. + ! If this is a restart run, load the state point data and binary source ! file if (restart_run) then @@ -452,12 +459,6 @@ contains end if end if - ! Reset global variables - current_batch = 0 - call k_generation % clear() - call entropy % clear() - need_depletion_rx = .false. - ! Set flag indicating initialization is done simulation_initialized = .true. From 4298c50c3fdf2796b0d6020b00889b8c1db691d9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 09:28:09 -0600 Subject: [PATCH 094/212] Use numpy 1.13 when testing since float formatting changed in 1.14 --- tools/ci/travis-install.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 3efadd6f36..4921534db9 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -4,8 +4,11 @@ set -ex # Install NJOY 2016 ./tools/ci/travis-install-njoy.sh -# Running OpenMC's setup.py requires numpy/cython already -pip install numpy cython +# Running OpenMC's setup.py requires numpy/cython already. NumPy float +# formatting changed in version 1.14, so stick with a lower version until we can +# handle it in our test suite +pip install 'numpy<1.14' +pip install cython # pytest installed by default -- make sure we get latest pip install --upgrade pytest From 563b1658919c43409e99c9618b3860d9efe54714 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Fri, 9 Feb 2018 18:56:39 -0500 Subject: [PATCH 095/212] Adjusted indentation --- src/physics.F90 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/physics.F90 b/src/physics.F90 index 721e3dd6c1..53a2cc2320 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -392,13 +392,13 @@ contains end if associate (rx => nuc % reactions(i), & - xs => nuc % reactions(i) % xs(i_temp)) - ! if energy is below threshold for this reaction, skip it - if (i_grid < xs % threshold) cycle + xs => nuc % reactions(i) % xs(i_temp)) + ! if energy is below threshold for this reaction, skip it + if (i_grid < xs % threshold) cycle - ! add to cumulative probability - prob = prob + ((ONE - f)*xs % value(i_grid - xs % threshold + 1) & - + f*(xs % value(i_grid - xs % threshold + 2))) + ! add to cumulative probability + prob = prob + ((ONE - f)*xs % value(i_grid - xs % threshold + 1) & + + f*(xs % value(i_grid - xs % threshold + 2))) end associate end do From bb4ac5a7b2365983bca8250d97d151426b7cbedb Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sat, 10 Feb 2018 01:04:45 -0500 Subject: [PATCH 096/212] Add IAPWS water density data --- openmc/data/data.py | 107 +++++++++++++++++++++++++++++ tests/unit_tests/test_data_misc.py | 10 +++ 2 files changed, 117 insertions(+) diff --git a/openmc/data/data.py b/openmc/data/data.py index ded6870188..8c0ed63728 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -1,6 +1,9 @@ import itertools import os import re +from warnings import warn + +from numpy import sqrt # Isotopic abundances from Meija J, Coplen T B, et al, "Isotopic compositions @@ -208,6 +211,110 @@ def atomic_weight(element): return None if weight == 0. else weight +def water_density(temperature, pressure=0.1013): + """Return the density of liquid water at a given temperature and pressure. + + The density is calculated from a polynomial fit using equations and values + from the 2012 version of the IAPWS-IF97 formulation. Only the equations + for region 1 are implemented here. + + Results are invalid for water vapor; pressures above 100 [MPa]; and + temperatures below 273.15 [K], above 623.15 [K], or above saturation. + + Reference: International Association for the Properties of Water and Steam, + "Revised Release on the IAPWS Industrial Formulation 1997 for the + Thermodynamic Properties of Water and Steam", IAPWS R7-97(2012). + + Parameters + ---------- + temperature : float + Water temperature in units of [K] + pressure : float + Water pressure in units of [MPa] + + Returns + ------- + float + Water density in units of [g / cm^3] + + """ + + # Make sure the temperature and pressure are inside the min/max region 1 + # bounds. (Relax the 273.15 bound to 273 in case a user wants 0 deg C data + # but they only use 3 digits for their conversion to K.) + if pressure > 100.0: + warn("Results are not valid for pressures above 100 MPa.") + if pressure < 0.0: + warn("Results are not valid for pressures below zero.") + if temperature < 273: + warn("Results are not valid for temperatures below 273.15 K.") + if temperature > 623.15: + warn("Results are not valid for temperatures above 623.15 K.") + + # IAPWS region 4 parameters + _n4 = [0.11670521452767e4, -0.72421316703206e6, -0.17073846940092e2, + 0.12020824702470e5, -0.32325550322333e7, 0.14915108613530e2, + -0.48232657361591e4, 0.40511340542057e6, -0.23855557567849, + 0.65017534844798e3] + + # Compute the saturation temperature at the given pressure. + beta = pressure**(0.25) + E = beta**2 + _n4[2] * beta + _n4[5] + F = _n4[0] * beta**2 + _n4[3] * beta + _n4[6] + G = _n4[1] * beta**2 + _n4[4] * beta + _n4[7] + D = 2.0 * G / (-F - sqrt(F**2 - 4 * E * G)) + T_sat = 0.5 * (_n4[9] + D + - sqrt((_n4[9] + D)**2 - 4.0 * (_n4[8] + _n4[9] * D))) + + # Make sure we aren't above saturation. (Relax this bound by .2 degrees + # for deg C to K conversions.) + if temperature > T_sat + 0.2: + warn("Results are not valid for temperatures above saturation " + "(above the boiling point).") + + # IAPWS region 1 parameters + R_GAS_CONSTANT = 0.461526 # kJ / kg / K + _ref_p = 16.53 # MPa + _ref_T = 1386 # K + _n1f = [0.14632971213167, -0.84548187169114, -0.37563603672040e1, + 0.33855169168385e1, -0.95791963387872, 0.15772038513228, + -0.16616417199501e-1, 0.81214629983568e-3, 0.28319080123804e-3, + -0.60706301565874e-3, -0.18990068218419e-1, -0.32529748770505e-1, + -0.21841717175414e-1, -0.52838357969930e-4, -0.47184321073267e-3, + -0.30001780793026e-3, 0.47661393906987e-4, -0.44141845330846e-5, + -0.72694996297594e-15, -0.31679644845054e-4, -0.28270797985312e-5, + -0.85205128120103e-9, -0.22425281908000e-5, -0.65171222895601e-6, + -0.14341729937924e-12, -0.40516996860117e-6, -0.12734301741641e-8, + -0.17424871230634e-9, -0.68762131295531e-18, 0.14478307828521e-19, + 0.26335781662795e-22, -0.11947622640071e-22, 0.18228094581404e-23, + -0.93537087292458e-25] + _I1f = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, + 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32] + _J1f = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, + 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41] + + # Nondimensionalize the pressure and temperature. + pi = pressure / _ref_p + tau = _ref_T / temperature + + # Compute the derivative of gamma (dimensionless Gibbs free energy) with + # respect to pi. + gamma1_pi = 0.0 + for i in range(34): + gamma1_pi -= (_n1f[i] * _I1f[i] * (7.1 - pi)**(_I1f[i] - 1) + * (tau - 1.222)**_J1f[i]) + + # Compute the leading coefficient. This sets the units at + # 1 [MPa] * [kg K / kJ] / [1 / K] + # = 1e6 [N / m^2] * 1e-3 [kg K / N / m] * [1 / K] + # = 1e3 [kg / m^3] + # = 1 [g / cm^3] + coeff = pressure / R_GAS_CONSTANT / temperature + + # Compute and return the density. + return coeff / pi / gamma1_pi + + # Values here are from the Committee on Data for Science and Technology # (CODATA) 2014 recommendation (doi:10.1103/RevModPhys.88.035009). diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index aeeb04c0fb..b33ef996fe 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -48,3 +48,13 @@ def test_thin(): x_thin, y_thin = openmc.data.thin(x, y) f = openmc.data.Tabulated1D(x_thin, y_thin) assert f(1.0) == pytest.approx(np.sin(1.0), 0.001) + + +def test_water_density(): + dens = openmc.data.water_density + # These test values are from IAPWS R7-97(2012). They are actually specific + # volumes so they need to be inverted. They also need to be divided by 1000 + # to convert from [kg / m^3] to [g / cm^2]. + assert dens(300.0, 3.0) == pytest.approx(1e-3/0.100215168e-2, 1e-6) + assert dens(300.0, 80.0) == pytest.approx(1e-3/0.971180894e-3, 1e-6) + assert dens(500.0, 3.0) == pytest.approx(1e-3/0.120241800e-2, 1e-6) From a06190ee407c14fd7a82cd0edf2fd89ce7e956d1 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sat, 10 Feb 2018 02:23:50 -0500 Subject: [PATCH 097/212] Add convenience function for boric acid Materials --- openmc/material.py | 70 +++++++++++++++++++++++++++++++ tests/unit_tests/test_material.py | 18 ++++++++ 2 files changed, 88 insertions(+) diff --git a/openmc/material.py b/openmc/material.py index e409d6536c..32b7d3a80d 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -973,3 +973,73 @@ class Materials(cv.CheckedList): # Write the XML Tree to the materials.xml file tree = ET.ElementTree(root_element) tree.write(path, xml_declaration=True, encoding='utf-8') + + +def make_boric_acid(boron_ppm, temperature=293., pressure=0.1013, density=None, + **kwargs): + """Return a Material with the composition of boric acid. + + The water density can either be given directly, or it can be determined from + a temperature and pressure. + + Parameters + ---------- + boron_ppm : float + The weight fraction in parts-per-million of elemental boron in the acid. + temperature : float + Water temperature in [K] used to compute water density. + pressure : float + Water pressure in [MPa] used to compute water density. + density : float + Water density in [g / cm^3]. If specified, this value overrides the + temperature and pressure arguments. + **kwargs + All keyword arguments are passed to the created Material object. + + Returns + ------- + openmc.Material + + """ + # Set the density of water, either from an explicitly given density or from + # temperature and pressure. + if density is not None: + water_density = density + else: + water_density = openmc.data.water_density(temperature, pressure) + + # Compute the density of the boric acid. + acid_density = water_density / (1 - boron_ppm * 1e-6) + + # Compute the molar mass of pure water. + hydrogen = openmc.Element('H') + oxygen = openmc.Element('O') + M_H2O = 0.0 + for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + + # Compute the molar mass of boron. + boron = openmc.Element('B') + M_B = 0.0 + for iso_name, frac, junk in boron.expand(1.0, 'ao'): + M_B += frac * openmc.data.atomic_mass(iso_name) + + # Compute the number fractions of each element. + frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O + frac_H = 2 * frac_H2O + frac_O = frac_H2O + frac_B = boron_ppm * 1e-6 / M_B + + # Build the material. + if density is None: + out = openmc.Material(temperature=temperature, **kwargs) + else: + out = openmc.Material(**kwargs) + out.add_element('H', frac_H, 'ao') + out.add_element('O', frac_O, 'ao') + out.add_element('B', frac_B, 'ao') + out.set_density('g/cc', acid_density) + out.add_s_alpha_beta('c_H_in_H2O') + return out diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index e92a2ac088..38495cb1ab 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -139,3 +139,21 @@ def test_materials(run_in_tmpdir): mats.cross_sections = '/some/fake/cross_sections.xml' mats.multipole_library = '/some/awesome/mp_lib/' mats.export_to_xml() + + +def test_boric_acid(): + # Test against reference values from the BEAVRS benchmark. + m = openmc.make_boric_acid(975, 566.5, 15.51, material_id=50) + assert m.density == pytest.approx(0.7405, 1e-3) + assert m.temperature == pytest.approx(566.5) + assert m._sab[0][0] == 'c_H_in_H2O' + ref_dens = {'B10':8.0023e-06, 'B11':3.2210e-05, 'H1':4.9458e-02, + 'O16':2.4672e-02} + nuc_dens = m.get_nuclide_atom_densities() + for nuclide in ref_dens: + assert nuc_dens[nuclide][1] == pytest.approx(ref_dens[nuclide], 1e-2) + assert m.id == 50 + + # Make sure the density override works + m = openmc.make_boric_acid(975, 566.5, 15.51, 0.9) + assert m.density == pytest.approx(0.9, 1e-3) From 9c53c085d6b81125f8cd3835ee40c2fc7f207f63 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sun, 11 Feb 2018 15:01:51 -0500 Subject: [PATCH 098/212] Change boric_acid to borated_water; add more units --- openmc/data/data.py | 7 +-- openmc/material.py | 70 ----------------------- openmc/model/funcs.py | 95 +++++++++++++++++++++++++++++++ tests/unit_tests/test_material.py | 16 ++++-- 4 files changed, 110 insertions(+), 78 deletions(-) diff --git a/openmc/data/data.py b/openmc/data/data.py index 8c0ed63728..45a4406dbe 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -216,10 +216,9 @@ def water_density(temperature, pressure=0.1013): The density is calculated from a polynomial fit using equations and values from the 2012 version of the IAPWS-IF97 formulation. Only the equations - for region 1 are implemented here. - - Results are invalid for water vapor; pressures above 100 [MPa]; and - temperatures below 273.15 [K], above 623.15 [K], or above saturation. + for region 1 are implemented here. Region 1 is limited to liquid water + below 100 [MPa] with a temperature above 273.15 [K], below 623.15 [K], and + below saturation. Reference: International Association for the Properties of Water and Steam, "Revised Release on the IAPWS Industrial Formulation 1997 for the diff --git a/openmc/material.py b/openmc/material.py index 32b7d3a80d..e409d6536c 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -973,73 +973,3 @@ class Materials(cv.CheckedList): # Write the XML Tree to the materials.xml file tree = ET.ElementTree(root_element) tree.write(path, xml_declaration=True, encoding='utf-8') - - -def make_boric_acid(boron_ppm, temperature=293., pressure=0.1013, density=None, - **kwargs): - """Return a Material with the composition of boric acid. - - The water density can either be given directly, or it can be determined from - a temperature and pressure. - - Parameters - ---------- - boron_ppm : float - The weight fraction in parts-per-million of elemental boron in the acid. - temperature : float - Water temperature in [K] used to compute water density. - pressure : float - Water pressure in [MPa] used to compute water density. - density : float - Water density in [g / cm^3]. If specified, this value overrides the - temperature and pressure arguments. - **kwargs - All keyword arguments are passed to the created Material object. - - Returns - ------- - openmc.Material - - """ - # Set the density of water, either from an explicitly given density or from - # temperature and pressure. - if density is not None: - water_density = density - else: - water_density = openmc.data.water_density(temperature, pressure) - - # Compute the density of the boric acid. - acid_density = water_density / (1 - boron_ppm * 1e-6) - - # Compute the molar mass of pure water. - hydrogen = openmc.Element('H') - oxygen = openmc.Element('O') - M_H2O = 0.0 - for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): - M_H2O += frac * openmc.data.atomic_mass(iso_name) - for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): - M_H2O += frac * openmc.data.atomic_mass(iso_name) - - # Compute the molar mass of boron. - boron = openmc.Element('B') - M_B = 0.0 - for iso_name, frac, junk in boron.expand(1.0, 'ao'): - M_B += frac * openmc.data.atomic_mass(iso_name) - - # Compute the number fractions of each element. - frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O - frac_H = 2 * frac_H2O - frac_O = frac_H2O - frac_B = boron_ppm * 1e-6 / M_B - - # Build the material. - if density is None: - out = openmc.Material(temperature=temperature, **kwargs) - else: - out = openmc.Material(**kwargs) - out.add_element('H', frac_H, 'ao') - out.add_element('O', frac_O, 'ao') - out.add_element('B', frac_B, 'ao') - out.set_density('g/cc', acid_density) - out.add_s_alpha_beta('c_H_in_H2O') - return out diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index 6013f6caee..b8984ada03 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -5,6 +5,7 @@ from numbers import Real from openmc import XPlane, YPlane, Plane, ZCylinder from openmc.checkvalue import check_type, check_value +import openmc.data def get_rectangular_prism(width, height, axis='z', origin=(0., 0.), @@ -252,6 +253,100 @@ def get_hexagonal_prism(edge_length=1., orientation='y', origin=(0., 0.), return prism +def make_borated_water(boron_ppm, temperature=293., pressure=0.1013, + temp_unit='K', press_unit='MPa', density=None, **kwargs): + """Return a Material with the composition of boron dissolved in water. + + The water density can be determined from a temperature and pressure, or it + can be set directly. + + The concentration of boron has no effect on the stoichometric ratio of H + and O---they are fixed at 2-1. + + Parameters + ---------- + boron_ppm : float + The weight fraction in parts-per-million of elemental boron in the + water. + temperature : float + Temperature in [K] used to compute water density. + pressure : float + Pressure in [MPa] used to compute water density. + temp_unit : str + The units used for the `temperature` argument. Valid units are 'K', + 'C', and 'F'. + press_unit : str + The units used for the `pressure` argument. Valid units are 'MPa' and + 'psi'. + density : float + Water density in [g / cm^3]. If specified, this value overrides the + temperature and pressure arguments. + **kwargs + All keyword arguments are passed to the created Material object. + + Returns + ------- + openmc.Material + + """ + # Perform any necessary unit conversions. + check_value('temperature unit', temp_unit, ('K', 'C', 'F')) + if temp_unit == 'K': + T = temperature + elif temp_unit == 'C': + T = temperature + 273.15 + elif temp_unit == 'F': + T = (temperature + 459.67) * 5.0 / 9.0 + check_value('pressure unit', press_unit, ('MPa', 'psi')) + if press_unit == 'MPa': + P = pressure + elif press_unit == 'psi': + P = pressure * 0.006895 + + # Set the density of water, either from an explicitly given density or from + # temperature and pressure. + if density is not None: + water_density = density + else: + water_density = openmc.data.water_density(T, P) + + # Compute the density of the solution. + solution_density = water_density / (1 - boron_ppm * 1e-6) + + # Compute the molar mass of pure water. + hydrogen = openmc.Element('H') + oxygen = openmc.Element('O') + M_H2O = 0.0 + for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + + # Compute the molar mass of boron. + boron = openmc.Element('B') + M_B = 0.0 + for iso_name, frac, junk in boron.expand(1.0, 'ao'): + M_B += frac * openmc.data.atomic_mass(iso_name) + + # Compute the number fractions of each element. + frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O + frac_H = 2 * frac_H2O + frac_O = frac_H2O + frac_B = boron_ppm * 1e-6 / M_B + + # Build the material. + if density is None: + out = openmc.Material(temperature=T, **kwargs) + else: + out = openmc.Material(**kwargs) + out.add_element('H', frac_H, 'ao') + out.add_element('O', frac_O, 'ao') + out.add_element('B', frac_B, 'ao') + out.set_density('g/cc', solution_density) + out.add_s_alpha_beta('c_H_in_H2O') + return out + + def subdivide(surfaces): """Create regions separated by a series of surfaces. diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 38495cb1ab..295153a9c1 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -141,9 +141,9 @@ def test_materials(run_in_tmpdir): mats.export_to_xml() -def test_boric_acid(): +def test_borated_water(): # Test against reference values from the BEAVRS benchmark. - m = openmc.make_boric_acid(975, 566.5, 15.51, material_id=50) + m = openmc.model.make_borated_water(975, 566.5, 15.51, material_id=50) assert m.density == pytest.approx(0.7405, 1e-3) assert m.temperature == pytest.approx(566.5) assert m._sab[0][0] == 'c_H_in_H2O' @@ -154,6 +154,14 @@ def test_boric_acid(): assert nuc_dens[nuclide][1] == pytest.approx(ref_dens[nuclide], 1e-2) assert m.id == 50 - # Make sure the density override works - m = openmc.make_boric_acid(975, 566.5, 15.51, 0.9) + # Test the Celsius conversion. + m = openmc.model.make_borated_water(975, 293.35, 15.51, 'C') + assert m.density == pytest.approx(0.7405, 1e-3) + + # Test Fahrenheit and psi conversions. + m = openmc.model.make_borated_water(975, 560.0, 2250.0, 'F', 'psi') + assert m.density == pytest.approx(0.7405, 1e-3) + + # Test the density override + m = openmc.model.make_borated_water(975, 566.5, 15.51, density=0.9) assert m.density == pytest.approx(0.9, 1e-3) From e0d6640c4fb43edf3213efe62c05c1106575c5d9 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sun, 11 Feb 2018 15:03:48 -0500 Subject: [PATCH 099/212] Add make_borated_water and water_density to docs --- docs/source/pythonapi/data.rst | 1 + docs/source/pythonapi/model.rst | 6 +----- tests/unit_tests/test_data_misc.py | 2 +- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/source/pythonapi/data.rst b/docs/source/pythonapi/data.rst index 7f75ddaaaf..3c221906db 100644 --- a/docs/source/pythonapi/data.rst +++ b/docs/source/pythonapi/data.rst @@ -34,6 +34,7 @@ Core Functions openmc.data.atomic_mass openmc.data.linearize openmc.data.thin + openmc.data.water_density openmc.data.write_compact_458_library Angle-Energy Distributions diff --git a/docs/source/pythonapi/model.rst b/docs/source/pythonapi/model.rst index 4ba247468a..6aff6d4c25 100644 --- a/docs/source/pythonapi/model.rst +++ b/docs/source/pythonapi/model.rst @@ -5,11 +5,6 @@ Convenience Functions --------------------- -Several helper functions are available here. Ther first two create rectangular -and hexagonal prisms defined by the intersection of four and six surface -half-spaces, respectively. The last function takes a sequence of surfaces and -returns the regions that separate them. - .. autosummary:: :toctree: generated :nosignatures: @@ -17,6 +12,7 @@ returns the regions that separate them. openmc.model.get_hexagonal_prism openmc.model.get_rectangular_prism + openmc.model.make_borated_water openmc.model.subdivide TRISO Fuel Modeling diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index b33ef996fe..433d34adb9 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -54,7 +54,7 @@ def test_water_density(): dens = openmc.data.water_density # These test values are from IAPWS R7-97(2012). They are actually specific # volumes so they need to be inverted. They also need to be divided by 1000 - # to convert from [kg / m^3] to [g / cm^2]. + # to convert from [kg / m^3] to [g / cm^3]. assert dens(300.0, 3.0) == pytest.approx(1e-3/0.100215168e-2, 1e-6) assert dens(300.0, 80.0) == pytest.approx(1e-3/0.971180894e-3, 1e-6) assert dens(500.0, 3.0) == pytest.approx(1e-3/0.120241800e-2, 1e-6) From d34bdf9b98bd2c06da5e5282d9516cce041be4cc Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Sun, 11 Feb 2018 18:39:06 -0500 Subject: [PATCH 100/212] Address #967 comments --- docs/source/pythonapi/model.rst | 2 +- openmc/data/data.py | 65 +++++------ openmc/model/funcs.py | 186 +++++++++++++++--------------- tests/unit_tests/test_material.py | 8 +- 4 files changed, 129 insertions(+), 132 deletions(-) diff --git a/docs/source/pythonapi/model.rst b/docs/source/pythonapi/model.rst index 6aff6d4c25..9ed77f3666 100644 --- a/docs/source/pythonapi/model.rst +++ b/docs/source/pythonapi/model.rst @@ -10,9 +10,9 @@ Convenience Functions :nosignatures: :template: myfunction.rst + openmc.model.borated_water openmc.model.get_hexagonal_prism openmc.model.get_rectangular_prism - openmc.model.make_borated_water openmc.model.subdivide TRISO Fuel Modeling diff --git a/openmc/data/data.py b/openmc/data/data.py index 45a4406dbe..a7c0e536f6 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -251,19 +251,19 @@ def water_density(temperature, pressure=0.1013): warn("Results are not valid for temperatures above 623.15 K.") # IAPWS region 4 parameters - _n4 = [0.11670521452767e4, -0.72421316703206e6, -0.17073846940092e2, - 0.12020824702470e5, -0.32325550322333e7, 0.14915108613530e2, - -0.48232657361591e4, 0.40511340542057e6, -0.23855557567849, - 0.65017534844798e3] + n4 = [0.11670521452767e4, -0.72421316703206e6, -0.17073846940092e2, + 0.12020824702470e5, -0.32325550322333e7, 0.14915108613530e2, + -0.48232657361591e4, 0.40511340542057e6, -0.23855557567849, + 0.65017534844798e3] # Compute the saturation temperature at the given pressure. beta = pressure**(0.25) - E = beta**2 + _n4[2] * beta + _n4[5] - F = _n4[0] * beta**2 + _n4[3] * beta + _n4[6] - G = _n4[1] * beta**2 + _n4[4] * beta + _n4[7] + E = beta**2 + n4[2] * beta + n4[5] + F = n4[0] * beta**2 + n4[3] * beta + n4[6] + G = n4[1] * beta**2 + n4[4] * beta + n4[7] D = 2.0 * G / (-F - sqrt(F**2 - 4 * E * G)) - T_sat = 0.5 * (_n4[9] + D - - sqrt((_n4[9] + D)**2 - 4.0 * (_n4[8] + _n4[9] * D))) + T_sat = 0.5 * (n4[9] + D + - sqrt((n4[9] + D)**2 - 4.0 * (n4[8] + n4[9] * D))) # Make sure we aren't above saturation. (Relax this bound by .2 degrees # for deg C to K conversions.) @@ -273,38 +273,37 @@ def water_density(temperature, pressure=0.1013): # IAPWS region 1 parameters R_GAS_CONSTANT = 0.461526 # kJ / kg / K - _ref_p = 16.53 # MPa - _ref_T = 1386 # K - _n1f = [0.14632971213167, -0.84548187169114, -0.37563603672040e1, - 0.33855169168385e1, -0.95791963387872, 0.15772038513228, - -0.16616417199501e-1, 0.81214629983568e-3, 0.28319080123804e-3, - -0.60706301565874e-3, -0.18990068218419e-1, -0.32529748770505e-1, - -0.21841717175414e-1, -0.52838357969930e-4, -0.47184321073267e-3, - -0.30001780793026e-3, 0.47661393906987e-4, -0.44141845330846e-5, - -0.72694996297594e-15, -0.31679644845054e-4, -0.28270797985312e-5, - -0.85205128120103e-9, -0.22425281908000e-5, -0.65171222895601e-6, - -0.14341729937924e-12, -0.40516996860117e-6, -0.12734301741641e-8, - -0.17424871230634e-9, -0.68762131295531e-18, 0.14478307828521e-19, - 0.26335781662795e-22, -0.11947622640071e-22, 0.18228094581404e-23, - -0.93537087292458e-25] - _I1f = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, - 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32] - _J1f = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, - 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41] + ref_p = 16.53 # MPa + ref_T = 1386 # K + n1f = [0.14632971213167, -0.84548187169114, -0.37563603672040e1, + 0.33855169168385e1, -0.95791963387872, 0.15772038513228, + -0.16616417199501e-1, 0.81214629983568e-3, 0.28319080123804e-3, + -0.60706301565874e-3, -0.18990068218419e-1, -0.32529748770505e-1, + -0.21841717175414e-1, -0.52838357969930e-4, -0.47184321073267e-3, + -0.30001780793026e-3, 0.47661393906987e-4, -0.44141845330846e-5, + -0.72694996297594e-15, -0.31679644845054e-4, -0.28270797985312e-5, + -0.85205128120103e-9, -0.22425281908000e-5, -0.65171222895601e-6, + -0.14341729937924e-12, -0.40516996860117e-6, -0.12734301741641e-8, + -0.17424871230634e-9, -0.68762131295531e-18, 0.14478307828521e-19, + 0.26335781662795e-22, -0.11947622640071e-22, 0.18228094581404e-23, + -0.93537087292458e-25] + I1f = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, + 4, 4, 5, 8, 8, 21, 23, 29, 30, 31, 32] + J1f = [-2, -1, 0, 1, 2, 3, 4, 5, -9, -7, -1, 0, 1, 3, -3, 0, 1, 3, 17, -4, + 0, 6, -5, -2, 10, -8, -11, -6, -29, -31, -38, -39, -40, -41] # Nondimensionalize the pressure and temperature. - pi = pressure / _ref_p - tau = _ref_T / temperature + pi = pressure / ref_p + tau = ref_T / temperature # Compute the derivative of gamma (dimensionless Gibbs free energy) with # respect to pi. gamma1_pi = 0.0 - for i in range(34): - gamma1_pi -= (_n1f[i] * _I1f[i] * (7.1 - pi)**(_I1f[i] - 1) - * (tau - 1.222)**_J1f[i]) + for n, I, J in zip(n1f, I1f, J1f): + gamma1_pi -= n * I * (7.1 - pi)**(I - 1) * (tau - 1.222)**J # Compute the leading coefficient. This sets the units at - # 1 [MPa] * [kg K / kJ] / [1 / K] + # 1 [MPa] * [kg K / kJ] * [1 / K] # = 1e6 [N / m^2] * 1e-3 [kg K / N / m] * [1 / K] # = 1e3 [kg / m^3] # = 1 [g / cm^3] diff --git a/openmc/model/funcs.py b/openmc/model/funcs.py index b8984ada03..e974f93b1b 100644 --- a/openmc/model/funcs.py +++ b/openmc/model/funcs.py @@ -8,6 +8,98 @@ from openmc.checkvalue import check_type, check_value import openmc.data +def borated_water(boron_ppm, temperature=293., pressure=0.1013, temp_unit='K', + press_unit='MPa', density=None, **kwargs): + """Return a Material with the composition of boron dissolved in water. + + The water density can be determined from a temperature and pressure, or it + can be set directly. + + The concentration of boron has no effect on the stoichiometric ratio of H + and O---they are fixed at 2-1. + + Parameters + ---------- + boron_ppm : float + The weight fraction in parts-per-million of elemental boron in the + water. + temperature : float + Temperature in [K] used to compute water density. + pressure : float + Pressure in [MPa] used to compute water density. + temp_unit : {'K', 'C', 'F'} + The units used for the `temperature` argument. + press_unit : {'MPa', 'psi'} + The units used for the `pressure` argument. + density : float + Water density in [g / cm^3]. If specified, this value overrides the + temperature and pressure arguments. + **kwargs + All keyword arguments are passed to the created Material object. + + Returns + ------- + openmc.Material + + """ + # Perform any necessary unit conversions. + check_value('temperature unit', temp_unit, ('K', 'C', 'F')) + if temp_unit == 'K': + T = temperature + elif temp_unit == 'C': + T = temperature + 273.15 + elif temp_unit == 'F': + T = (temperature + 459.67) * 5.0 / 9.0 + check_value('pressure unit', press_unit, ('MPa', 'psi')) + if press_unit == 'MPa': + P = pressure + elif press_unit == 'psi': + P = pressure * 0.006895 + + # Set the density of water, either from an explicitly given density or from + # temperature and pressure. + if density is not None: + water_density = density + else: + water_density = openmc.data.water_density(T, P) + + # Compute the density of the solution. + solution_density = water_density / (1 - boron_ppm * 1e-6) + + # Compute the molar mass of pure water. + hydrogen = openmc.Element('H') + oxygen = openmc.Element('O') + M_H2O = 0.0 + for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): + M_H2O += frac * openmc.data.atomic_mass(iso_name) + + # Compute the molar mass of boron. + boron = openmc.Element('B') + M_B = 0.0 + for iso_name, frac, junk in boron.expand(1.0, 'ao'): + M_B += frac * openmc.data.atomic_mass(iso_name) + + # Compute the number fractions of each element. + frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O + frac_H = 2 * frac_H2O + frac_O = frac_H2O + frac_B = boron_ppm * 1e-6 / M_B + + # Build the material. + if density is None: + out = openmc.Material(temperature=T, **kwargs) + else: + out = openmc.Material(**kwargs) + out.add_element('H', frac_H, 'ao') + out.add_element('O', frac_O, 'ao') + out.add_element('B', frac_B, 'ao') + out.set_density('g/cc', solution_density) + out.add_s_alpha_beta('c_H_in_H2O') + return out + + def get_rectangular_prism(width, height, axis='z', origin=(0., 0.), boundary_type='transmission', corner_radius=0.): """Get an infinite rectangular prism from four planar surfaces. @@ -253,100 +345,6 @@ def get_hexagonal_prism(edge_length=1., orientation='y', origin=(0., 0.), return prism -def make_borated_water(boron_ppm, temperature=293., pressure=0.1013, - temp_unit='K', press_unit='MPa', density=None, **kwargs): - """Return a Material with the composition of boron dissolved in water. - - The water density can be determined from a temperature and pressure, or it - can be set directly. - - The concentration of boron has no effect on the stoichometric ratio of H - and O---they are fixed at 2-1. - - Parameters - ---------- - boron_ppm : float - The weight fraction in parts-per-million of elemental boron in the - water. - temperature : float - Temperature in [K] used to compute water density. - pressure : float - Pressure in [MPa] used to compute water density. - temp_unit : str - The units used for the `temperature` argument. Valid units are 'K', - 'C', and 'F'. - press_unit : str - The units used for the `pressure` argument. Valid units are 'MPa' and - 'psi'. - density : float - Water density in [g / cm^3]. If specified, this value overrides the - temperature and pressure arguments. - **kwargs - All keyword arguments are passed to the created Material object. - - Returns - ------- - openmc.Material - - """ - # Perform any necessary unit conversions. - check_value('temperature unit', temp_unit, ('K', 'C', 'F')) - if temp_unit == 'K': - T = temperature - elif temp_unit == 'C': - T = temperature + 273.15 - elif temp_unit == 'F': - T = (temperature + 459.67) * 5.0 / 9.0 - check_value('pressure unit', press_unit, ('MPa', 'psi')) - if press_unit == 'MPa': - P = pressure - elif press_unit == 'psi': - P = pressure * 0.006895 - - # Set the density of water, either from an explicitly given density or from - # temperature and pressure. - if density is not None: - water_density = density - else: - water_density = openmc.data.water_density(T, P) - - # Compute the density of the solution. - solution_density = water_density / (1 - boron_ppm * 1e-6) - - # Compute the molar mass of pure water. - hydrogen = openmc.Element('H') - oxygen = openmc.Element('O') - M_H2O = 0.0 - for iso_name, frac, junk in hydrogen.expand(2.0, 'ao'): - M_H2O += frac * openmc.data.atomic_mass(iso_name) - for iso_name, frac, junk in oxygen.expand(1.0, 'ao'): - M_H2O += frac * openmc.data.atomic_mass(iso_name) - - # Compute the molar mass of boron. - boron = openmc.Element('B') - M_B = 0.0 - for iso_name, frac, junk in boron.expand(1.0, 'ao'): - M_B += frac * openmc.data.atomic_mass(iso_name) - - # Compute the number fractions of each element. - frac_H2O = (1 - boron_ppm * 1e-6) / M_H2O - frac_H = 2 * frac_H2O - frac_O = frac_H2O - frac_B = boron_ppm * 1e-6 / M_B - - # Build the material. - if density is None: - out = openmc.Material(temperature=T, **kwargs) - else: - out = openmc.Material(**kwargs) - out.add_element('H', frac_H, 'ao') - out.add_element('O', frac_O, 'ao') - out.add_element('B', frac_B, 'ao') - out.set_density('g/cc', solution_density) - out.add_s_alpha_beta('c_H_in_H2O') - return out - - def subdivide(surfaces): """Create regions separated by a series of surfaces. diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 295153a9c1..2265215417 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -143,7 +143,7 @@ def test_materials(run_in_tmpdir): def test_borated_water(): # Test against reference values from the BEAVRS benchmark. - m = openmc.model.make_borated_water(975, 566.5, 15.51, material_id=50) + m = openmc.model.borated_water(975, 566.5, 15.51, material_id=50) assert m.density == pytest.approx(0.7405, 1e-3) assert m.temperature == pytest.approx(566.5) assert m._sab[0][0] == 'c_H_in_H2O' @@ -155,13 +155,13 @@ def test_borated_water(): assert m.id == 50 # Test the Celsius conversion. - m = openmc.model.make_borated_water(975, 293.35, 15.51, 'C') + m = openmc.model.borated_water(975, 293.35, 15.51, 'C') assert m.density == pytest.approx(0.7405, 1e-3) # Test Fahrenheit and psi conversions. - m = openmc.model.make_borated_water(975, 560.0, 2250.0, 'F', 'psi') + m = openmc.model.borated_water(975, 560.0, 2250.0, 'F', 'psi') assert m.density == pytest.approx(0.7405, 1e-3) # Test the density override - m = openmc.model.make_borated_water(975, 566.5, 15.51, density=0.9) + m = openmc.model.borated_water(975, 566.5, 15.51, density=0.9) assert m.density == pytest.approx(0.9, 1e-3) From 718474fb494cf9db307594d1fff867cd7ed80b31 Mon Sep 17 00:00:00 2001 From: Adam Nelson Date: Tue, 13 Feb 2018 06:35:50 -0500 Subject: [PATCH 101/212] Cleaned up index_inelastic_scatter a bit to address comments in #963" --- src/nuclide_header.F90 | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/nuclide_header.F90 b/src/nuclide_header.F90 index c0c5c2627d..8362f5d41e 100644 --- a/src/nuclide_header.F90 +++ b/src/nuclide_header.F90 @@ -303,7 +303,7 @@ contains real(8) :: temp_actual type(VectorInt) :: MTs type(VectorInt) :: temps_to_read - type(VectorInt) :: index_inelastic_scatter_vector + type(VectorInt) :: index_inelastic_scatter ! Get name of nuclide from group name_len = len(this % name) @@ -478,7 +478,7 @@ contains MTs % data(i) /= N_3NF .and. MTs % data(i) < 200 .and. & MTs % data(i) /= N_LEVEL .and. MTs % data(i) /= ELASTIC) then - call index_inelastic_scatter_vector % push_back(i) + call index_inelastic_scatter % push_back(i) end if call close_group(rx_group) @@ -486,10 +486,9 @@ contains call close_group(rxs_group) ! Recast to a regular array to save space - allocate(this % index_inelastic_scatter( & - index_inelastic_scatter_vector % size())) - this % index_inelastic_scatter = index_inelastic_scatter_vector % data(:) - call index_inelastic_scatter_vector % clear() + allocate(this % index_inelastic_scatter(index_inelastic_scatter % size())) + this % index_inelastic_scatter = & + index_inelastic_scatter % data(1: index_inelastic_scatter % size()) ! Read unresolved resonance probability tables if present if (object_exists(group_id, 'urr')) then From f8764416d2c727c5b1693c297c3f7994c8314d1b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 13:29:04 -0600 Subject: [PATCH 102/212] Copy OpenDeplete files from commit 2d804c227a --- chains/chain_simple.xml | 49 + chains/chain_test.xml | 23 + docs/source/pythonapi/deplete/index.rst | 56 ++ .../pythonapi/deplete/integrator.CRAM16.rst | 6 + .../pythonapi/deplete/integrator.CRAM48.rst | 6 + .../pythonapi/deplete/integrator.cecm.rst | 6 + .../deplete/integrator.predictor.rst | 6 + .../deplete/integrator.save_results.rst | 6 + .../deplete/opendeplete.Concentrations.rst | 30 + .../deplete/opendeplete.ReactionRates.rst | 30 + .../pythonapi/deplete/opendeplete.Results.rst | 22 + openmc/deplete/__init__.py | 24 + openmc/deplete/atom_number.py | 236 +++++ openmc/deplete/depletion_chain.py | 472 ++++++++++ openmc/deplete/dummy_comm.py | 27 + openmc/deplete/function.py | 114 +++ openmc/deplete/integrator/__init__.py | 11 + openmc/deplete/integrator/cecm.py | 133 +++ openmc/deplete/integrator/cram.py | 185 ++++ openmc/deplete/integrator/predictor.py | 100 ++ openmc/deplete/integrator/save_results.py | 46 + openmc/deplete/nuclide.py | 178 ++++ openmc/deplete/openmc_wrapper.py | 853 ++++++++++++++++++ openmc/deplete/reaction_rates.py | 113 +++ openmc/deplete/results.py | 454 ++++++++++ openmc/deplete/utilities.py | 98 ++ scripts/example_geometry.py | 358 ++++++++ scripts/example_plot.py | 46 + scripts/example_run.py | 39 + scripts/make_chain.py | 60 ++ tests/deplete_tests/__init__.py | 0 tests/deplete_tests/dummy_geometry.py | 165 ++++ tests/deplete_tests/example_geometry.py | 1 + tests/deplete_tests/test_atom_number.py | 180 ++++ tests/deplete_tests/test_cecm_regression.py | 69 ++ tests/deplete_tests/test_cram.py | 48 + tests/deplete_tests/test_depletion_chain.py | 197 ++++ tests/deplete_tests/test_full.py | 119 +++ tests/deplete_tests/test_integrator.py | 116 +++ tests/deplete_tests/test_nuclide.py | 121 +++ .../test_predictor_regression.py | 68 ++ tests/deplete_tests/test_reaction_rates.py | 86 ++ tests/deplete_tests/test_reference.h5 | Bin 0 -> 165384 bytes tests/deplete_tests/test_utilities.py | 68 ++ 44 files changed, 5025 insertions(+) create mode 100644 chains/chain_simple.xml create mode 100644 chains/chain_test.xml create mode 100644 docs/source/pythonapi/deplete/index.rst create mode 100644 docs/source/pythonapi/deplete/integrator.CRAM16.rst create mode 100644 docs/source/pythonapi/deplete/integrator.CRAM48.rst create mode 100644 docs/source/pythonapi/deplete/integrator.cecm.rst create mode 100644 docs/source/pythonapi/deplete/integrator.predictor.rst create mode 100644 docs/source/pythonapi/deplete/integrator.save_results.rst create mode 100644 docs/source/pythonapi/deplete/opendeplete.Concentrations.rst create mode 100644 docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst create mode 100644 docs/source/pythonapi/deplete/opendeplete.Results.rst create mode 100644 openmc/deplete/__init__.py create mode 100644 openmc/deplete/atom_number.py create mode 100644 openmc/deplete/depletion_chain.py create mode 100644 openmc/deplete/dummy_comm.py create mode 100644 openmc/deplete/function.py create mode 100644 openmc/deplete/integrator/__init__.py create mode 100644 openmc/deplete/integrator/cecm.py create mode 100644 openmc/deplete/integrator/cram.py create mode 100644 openmc/deplete/integrator/predictor.py create mode 100644 openmc/deplete/integrator/save_results.py create mode 100644 openmc/deplete/nuclide.py create mode 100644 openmc/deplete/openmc_wrapper.py create mode 100644 openmc/deplete/reaction_rates.py create mode 100644 openmc/deplete/results.py create mode 100644 openmc/deplete/utilities.py create mode 100644 scripts/example_geometry.py create mode 100644 scripts/example_plot.py create mode 100644 scripts/example_run.py create mode 100644 scripts/make_chain.py create mode 100644 tests/deplete_tests/__init__.py create mode 100644 tests/deplete_tests/dummy_geometry.py create mode 120000 tests/deplete_tests/example_geometry.py create mode 100644 tests/deplete_tests/test_atom_number.py create mode 100644 tests/deplete_tests/test_cecm_regression.py create mode 100644 tests/deplete_tests/test_cram.py create mode 100644 tests/deplete_tests/test_depletion_chain.py create mode 100644 tests/deplete_tests/test_full.py create mode 100644 tests/deplete_tests/test_integrator.py create mode 100644 tests/deplete_tests/test_nuclide.py create mode 100644 tests/deplete_tests/test_predictor_regression.py create mode 100644 tests/deplete_tests/test_reaction_rates.py create mode 100644 tests/deplete_tests/test_reference.h5 create mode 100644 tests/deplete_tests/test_utilities.py diff --git a/chains/chain_simple.xml b/chains/chain_simple.xml new file mode 100644 index 0000000000..345da2237d --- /dev/null +++ b/chains/chain_simple.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 1.093250e-04 2.087260e-04 2.780820e-02 6.759540e-03 2.392300e-02 4.356330e-05 + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 6.142710e-5 1.483250e-04 0.0292737 0.002566345 0.0219242 4.9097e-6 + + + + + + + 2.53000e-02 + + Gd157 Gd156 I135 Xe135 Xe136 Cs135 + 4.141120e-04 7.605360e-04 0.0135457 0.00026864 0.0024432 3.7100E-07 + + + + diff --git a/chains/chain_test.xml b/chains/chain_test.xml new file mode 100644 index 0000000000..5985704063 --- /dev/null +++ b/chains/chain_test.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + 0.0253 + + A B + 0.0292737 0.002566345 + + + + diff --git a/docs/source/pythonapi/deplete/index.rst b/docs/source/pythonapi/deplete/index.rst new file mode 100644 index 0000000000..55380c7a1c --- /dev/null +++ b/docs/source/pythonapi/deplete/index.rst @@ -0,0 +1,56 @@ +.. _api: + +================= +API Documentation +================= + +Integrators +----------- + +.. toctree:: + :maxdepth: 2 + + integrator.predictor + integrator.cecm + +Integrator Helper Functions +--------------------------- +.. toctree:: + :maxdepth: 2 + + integrator.CRAM16 + integrator.CRAM48 + integrator.save_results + +Metaclasses +----------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + opendeplete.Settings + opendeplete.Operator + +OpenMC Classes +-------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + + opendeplete.OpenMCSettings + opendeplete.Materials + opendeplete.OpenMCOperator + +Data Classes +------------ +.. autosummary:: + :toctree: generated + :nosignatures: + + opendeplete.AtomNumber + opendeplete.DepletionChain + opendeplete.Nuclide + opendeplete.ReactionRates + opendeplete.Results diff --git a/docs/source/pythonapi/deplete/integrator.CRAM16.rst b/docs/source/pythonapi/deplete/integrator.CRAM16.rst new file mode 100644 index 0000000000..f9eba273ed --- /dev/null +++ b/docs/source/pythonapi/deplete/integrator.CRAM16.rst @@ -0,0 +1,6 @@ +integrator\.CRAM16 +================== + +.. currentmodule:: opendeplete.integrator + +.. autofunction:: CRAM16 diff --git a/docs/source/pythonapi/deplete/integrator.CRAM48.rst b/docs/source/pythonapi/deplete/integrator.CRAM48.rst new file mode 100644 index 0000000000..d7467a418a --- /dev/null +++ b/docs/source/pythonapi/deplete/integrator.CRAM48.rst @@ -0,0 +1,6 @@ +integrator\.CRAM48 +================== + +.. currentmodule:: opendeplete.integrator + +.. autofunction:: CRAM48 diff --git a/docs/source/pythonapi/deplete/integrator.cecm.rst b/docs/source/pythonapi/deplete/integrator.cecm.rst new file mode 100644 index 0000000000..507a638f69 --- /dev/null +++ b/docs/source/pythonapi/deplete/integrator.cecm.rst @@ -0,0 +1,6 @@ +integrator\.cecm +================= + +.. currentmodule:: opendeplete.integrator + +.. autofunction:: cecm diff --git a/docs/source/pythonapi/deplete/integrator.predictor.rst b/docs/source/pythonapi/deplete/integrator.predictor.rst new file mode 100644 index 0000000000..d6c0fd827c --- /dev/null +++ b/docs/source/pythonapi/deplete/integrator.predictor.rst @@ -0,0 +1,6 @@ +integrator\.predictor +===================== + +.. currentmodule:: opendeplete.integrator + +.. autofunction:: predictor diff --git a/docs/source/pythonapi/deplete/integrator.save_results.rst b/docs/source/pythonapi/deplete/integrator.save_results.rst new file mode 100644 index 0000000000..5c21dcb664 --- /dev/null +++ b/docs/source/pythonapi/deplete/integrator.save_results.rst @@ -0,0 +1,6 @@ +integrator\.save_results +======================== + +.. currentmodule:: opendeplete.integrator + +.. autofunction:: save_results diff --git a/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst b/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst new file mode 100644 index 0000000000..6fa07a970b --- /dev/null +++ b/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst @@ -0,0 +1,30 @@ +opendeplete.Concentrations +========================== + +.. currentmodule:: opendeplete + +.. autoclass:: Concentrations + + + .. automethod:: __init__ + + + .. rubric:: Methods + + .. autosummary:: + + ~Concentrations.__init__ + ~Concentrations.convert_nested_dict + + + + + + .. rubric:: Attributes + + .. autosummary:: + + ~Concentrations.n_cell + ~Concentrations.n_nuc + + \ No newline at end of file diff --git a/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst b/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst new file mode 100644 index 0000000000..99e048b565 --- /dev/null +++ b/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst @@ -0,0 +1,30 @@ +opendeplete.ReactionRates +========================= + +.. currentmodule:: opendeplete + +.. autoclass:: ReactionRates + + + .. automethod:: __init__ + + + .. rubric:: Methods + + .. autosummary:: + + ~ReactionRates.__init__ + + + + + + .. rubric:: Attributes + + .. autosummary:: + + ~ReactionRates.n_cell + ~ReactionRates.n_nuc + ~ReactionRates.n_react + + \ No newline at end of file diff --git a/docs/source/pythonapi/deplete/opendeplete.Results.rst b/docs/source/pythonapi/deplete/opendeplete.Results.rst new file mode 100644 index 0000000000..0ab8a1f711 --- /dev/null +++ b/docs/source/pythonapi/deplete/opendeplete.Results.rst @@ -0,0 +1,22 @@ +opendeplete.Results +=================== + +.. currentmodule:: opendeplete + +.. autoclass:: Results + + + .. automethod:: __init__ + + + .. rubric:: Methods + + .. autosummary:: + + ~Results.__init__ + + + + + + \ No newline at end of file diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py new file mode 100644 index 0000000000..994a51e12c --- /dev/null +++ b/openmc/deplete/__init__.py @@ -0,0 +1,24 @@ +""" +OpenDeplete +=========== + +A simple depletion front-end tool. +""" + +from .dummy_comm import DummyCommunicator +try: + from mpi4py import MPI + comm = MPI.COMM_WORLD + have_mpi = True +except ImportError: + comm = DummyCommunicator() + have_mpi = False + +from .nuclide import * +from .depletion_chain import * +from .openmc_wrapper import * +from .reaction_rates import * +from .function import * +from .results import * +from .integrator import * +from .utilities import * diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py new file mode 100644 index 0000000000..03bedbf531 --- /dev/null +++ b/openmc/deplete/atom_number.py @@ -0,0 +1,236 @@ +"""AtomNumber module. + +An ndarray to store atom densities with string, integer, or slice indexing. +""" + +import numpy as np + + +class AtomNumber(object): + """ AtomNumber module. + + An ndarray to store atom densities with string, integer, or slice indexing. + + Parameters + ---------- + mat_to_ind : OrderedDict of str to int + A dictionary mapping material ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + volume : OrderedDict of int to float + Volume of geometry. + n_mat_burn : int + Number of materials to be burned. + n_nuc_burn : int + Number of nuclides to be burned. + + Attributes + ---------- + mat_to_ind : OrderedDict of str to int + A dictionary mapping cell ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + volume : numpy.array + Volume of geometry indexed by mat_to_ind. If a volume is not found, + it defaults to 1 so that reading density still works correctly. + n_mat_burn : int + Number of materials to be burned. + n_nuc_burn : int + Number of nuclides to be burned. + n_mat : int + Number of materials. + n_nuc : int + Number of nucs. + number : numpy.array + Array storing total atoms indexed by the above dictionaries. + burn_nuc_list : list of str + A list of all nuclide material names. Used for sorting the simulation. + burn_mat_list : list of str + A list of all burning material names. Used for sorting the simulation. + """ + + def __init__(self, mat_to_ind, nuc_to_ind, volume, n_mat_burn, n_nuc_burn): + + self.mat_to_ind = mat_to_ind + self.nuc_to_ind = nuc_to_ind + + self.volume = np.ones(self.n_mat) + + for mat in volume: + if str(mat) in self.mat_to_ind: + ind = self.mat_to_ind[str(mat)] + self.volume[ind] = volume[mat] + + self.n_mat_burn = n_mat_burn + self.n_nuc_burn = n_nuc_burn + + self.number = np.zeros((self.n_mat, self.n_nuc)) + + # For performance, create storage for burn_nuc_list, burn_mat_list + self._burn_nuc_list = None + self._burn_mat_list = None + + def __getitem__(self, pos): + """ Retrieves total atom number from AtomNumber. + + Parameters + ---------- + pos : tuple + A two-length tuple containing a material index and a nuc index. + These indexes can be strings (which get converted to integers via + the dictionaries), integers used directly, or slices. + + Returns + ------- + numpy.array + The value indexed from self.number. + """ + + mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + return self.number[mat, nuc] + + def __setitem__(self, pos, val): + """ Sets total atom number into AtomNumber. + + Parameters + ---------- + pos : tuple + A two-length tuple containing a material index and a nuc index. + These indexes can be strings (which get converted to integers via + the dictionaries), integers used directly, or slices. + val : float + The value to set the array to. + """ + + mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + self.number[mat, nuc] = val + + def get_atom_density(self, mat, nuc): + """ Accesses atom density instead of total number. + + Parameters + ---------- + mat : str, int or slice + Material index. + nuc : str, int or slice + Nuclide index. + + Returns + ------- + numpy.array + The density indexed. + """ + + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + return self[mat, nuc] / self.volume[mat] + + def set_atom_density(self, mat, nuc, val): + """ Sets atom density instead of total number. + + Parameters + ---------- + mat : str, int or slice + Material index. + nuc : str, int or slice + Nuclide index. + val : numpy.array + Array of values to set. + """ + + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + self[mat, nuc] = val * self.volume[mat] + + def get_mat_slice(self, mat): + """ Gets atom quantity indexed by mats for all burned nuclides + + Parameters + ---------- + mat : str, int or slice + Material index. + + Returns + ------- + numpy.array + The slice requested. + """ + + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + + return self[mat, 0:self.n_nuc_burn] + + def set_mat_slice(self, mat, val): + """ Sets atom quantity indexed by mats for all burned nuclides + + Parameters + ---------- + mat : str, int or slice + Material index. + val : numpy.array + The slice to set. + """ + + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + + self[mat, 0:self.n_nuc_burn] = val + + @property + def n_mat(self): + """Number of materials.""" + return len(self.mat_to_ind) + + @property + def n_nuc(self): + """Number of nuclides.""" + return len(self.nuc_to_ind) + + @property + def burn_nuc_list(self): + """ burn_nuc_list : list of str + A list of all nuclide material names. Used for sorting the simulation. + """ + + if self._burn_nuc_list is None: + self._burn_nuc_list = [None] * self.n_nuc_burn + + for nuc in self.nuc_to_ind: + ind = self.nuc_to_ind[nuc] + if ind < self.n_nuc_burn: + self._burn_nuc_list[ind] = nuc + + return self._burn_nuc_list + + @property + def burn_mat_list(self): + """ burn_mat_list : list of str + A list of all burning material names. Used for sorting the simulation. + """ + + if self._burn_mat_list is None: + self._burn_mat_list = [None] * self.n_mat_burn + + for mat in self.mat_to_ind: + ind = self.mat_to_ind[mat] + if ind < self.n_mat_burn: + self._burn_mat_list[ind] = mat + + return self._burn_mat_list diff --git a/openmc/deplete/depletion_chain.py b/openmc/deplete/depletion_chain.py new file mode 100644 index 0000000000..05cc9db435 --- /dev/null +++ b/openmc/deplete/depletion_chain.py @@ -0,0 +1,472 @@ +"""depletion_chain module. + +This module contains information about a depletion chain. A depletion chain is +loaded from an .xml file and all the nuclides are linked together. +""" + +from collections import OrderedDict, defaultdict +from io import StringIO +from itertools import chain +import math +import re +import os + +from tqdm import tqdm +import scipy.sparse as sp +import openmc.data +# Try to use lxml if it is available. It preserves the order of attributes and +# provides a pretty-printer by default. If not available, use OpenMC function to +# pretty print. +try: + import lxml.etree as ET + _have_lxml = True +except ImportError: + import xml.etree.ElementTree as ET + from openmc.clean_xml import clean_xml_indentation + _have_lxml = False + +from .nuclide import Nuclide, DecayTuple, ReactionTuple + + +# tuple of (reaction name, possible MT values, (dA, dZ)) where dA is the change +# in the mass number and dZ is the change in the atomic number +_REACTIONS = [ + ('(n,2n)', set(chain([16], range(875, 892))), (-1, 0)), + ('(n,3n)', {17}, (-2, 0)), + ('(n,4n)', {37}, (-3, 0)), + ('(n,gamma)', {102}, (1, 0)), + ('(n,p)', set(chain([103], range(600, 650))), (0, -1)), + ('(n,a)', set(chain([107], range(800, 850))), (-3, -2)) +] + + +def _get_zai(s): + """Get ZAI value (10000*z + 10*A + metastable state) for sorting purposes""" + symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', s).groups() + Z = openmc.data.ATOMIC_NUMBER[symbol] + A = int(A) + state = int(state[2:]) if state else 0 + return 10000*Z + 10*A + state + + +def replace_missing(product, decay_data): + """Replace missing product with suitable decay daughter. + + Parameters + ---------- + product : str + Name of product in GND format, e.g. 'Y86_m1'. + decay_data : dict + Dictionary of decay data + + Returns + ------- + product : str + Replacement for missing product in GND format. + + """ + + symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_m\d+)?)', + product).groups() + Z = openmc.data.ATOMIC_NUMBER[symbol] + A = int(A) + + # First check if ground state is available + if state: + metastable_state = int(state[2:]) + product = '{}{}'.format(symbol, A) + + # Find isotope with longest half-life + half_life = 0.0 + for nuclide, data in decay_data.items(): + m = re.match(r'{}(\d+)(?:_m\d+)?'.format(symbol), nuclide) + if m: + # If we find a stable nuclide, stop search + if data.nuclide['stable']: + mass_longest_lived = int(m.group(1)) + break + if data.half_life.nominal_value > half_life: + mass_longest_lived = int(m.group(1)) + half_life = data.half_life.nominal_value + + # If mass number of longest-lived isotope is less than that of missing + # product, assume it undergoes beta-. Otherwise assume beta+. + beta_minus = (mass_longest_lived < A) + + # Iterate until we find an existing nuclide + while product not in decay_data: + if Z > 98: + Z -= 2 + A -= 4 + else: + if beta_minus: + Z += 1 + else: + Z -= 1 + product = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) + + return product + + +class DepletionChain(object): + """ The DepletionChain class. + + This class contains a full representation of a depletion chain. + + Attributes + ---------- + n_nuclides : int + Number of nuclides in chain. + nuclides : list of Nuclide + List of nuclides in chain. + nuclide_dict : OrderedDict of str to int + Maps a nuclide name to an index in nuclides. + nuc_to_react_ind : OrderedDict of str to int + Dictionary mapping a nuclide name to an index in ReactionRates. + react_to_ind : OrderedDict of str to int + Dictionary mapping a reaction name to an index in ReactionRates. + + """ + + def __init__(self): + self.nuclides = [] + self.nuclide_dict = OrderedDict() + self.nuc_to_react_ind = OrderedDict() + self.react_to_ind = OrderedDict() + + @property + def n_nuclides(self): + """Number of nuclides in chain.""" + return len(self.nuclides) + + @classmethod + def from_endf(cls, decay_files, fpy_files, neutron_files): + """Create a depletion chain from ENDF files. + + Parameters + ---------- + decay_files : list of str + List of ENDF decay sub-library files + fpy_files : list of str + List of ENDF neutron-induced fission product yield sub-library files + neutron_files : list of str + List of ENDF neutron reaction sub-library files + + """ + depl_chain = cls() + + # Create dictionary mapping target to filename + reactions = {} + with tqdm(neutron_files) as pbar: + for f in pbar: + pbar.set_description('Processing {}'.format(os.path.basename(f))) + evaluation = openmc.data.endf.Evaluation(f) + name = evaluation.gnd_name + reactions[name] = {} + for mf, mt, nc, mod in evaluation.reaction_list: + if mf == 3: + file_obj = StringIO(evaluation.section[3, mt]) + openmc.data.endf.get_head_record(file_obj) + q_value = openmc.data.endf.get_cont_record(file_obj)[1] + reactions[name][mt] = q_value + + # Determine what decay and FPY nuclides are available + decay_data = {} + with tqdm(decay_files) as pbar: + for f in pbar: + pbar.set_description('Processing {}'.format(os.path.basename(f))) + data = openmc.data.Decay(f) + decay_data[data.nuclide['name']] = data + + fpy_data = {} + with tqdm(fpy_files) as pbar: + for f in pbar: + pbar.set_description('Processing {}'.format(os.path.basename(f))) + data = openmc.data.FissionProductYields(f) + fpy_data[data.nuclide['name']] = data + + print('Creating depletion_chain...') + missing_daughter = [] + missing_rx_product = [] + missing_fpy = [] + missing_fp = [] + + reaction_index = 0 + for idx, parent in enumerate(sorted(decay_data, key=_get_zai)): + data = decay_data[parent] + + nuclide = Nuclide() + nuclide.name = parent + + depl_chain.nuclides.append(nuclide) + depl_chain.nuclide_dict[parent] = idx + + if not data.nuclide['stable'] and data.half_life.nominal_value != 0.0: + nuclide.half_life = data.half_life.nominal_value + nuclide.decay_energy = sum(E.nominal_value for E in + data.average_energies.values()) + sum_br = 0.0 + for i, mode in enumerate(data.modes): + type_ = ','.join(mode.modes) + if mode.daughter in decay_data: + target = mode.daughter + else: + print('missing {} {} {}'.format(parent, ','.join(mode.modes), mode.daughter)) + target = replace_missing(mode.daughter, decay_data) + + # Write branching ratio, taking care to ensure sum is unity + br = mode.branching_ratio.nominal_value + sum_br += br + if i == len(data.modes) - 1 and sum_br != 1.0: + br = 1.0 - sum(m.branching_ratio.nominal_value + for m in data.modes[:-1]) + + # Append decay mode + nuclide.decay_modes.append(DecayTuple(type_, target, br)) + + if parent in reactions: + reactions_available = set(reactions[parent].keys()) + for name, mts, changes in _REACTIONS: + if mts & reactions_available: + delta_A, delta_Z = changes + A = data.nuclide['mass_number'] + delta_A + Z = data.nuclide['atomic_number'] + delta_Z + daughter = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) + + if name not in depl_chain.react_to_ind: + depl_chain.react_to_ind[name] = reaction_index + reaction_index += 1 + + if daughter not in decay_data: + missing_rx_product.append((parent, name, daughter)) + + # Store Q value + for mt in sorted(mts): + if mt in reactions[parent]: + q_value = reactions[parent][mt] + break + else: + q_value = 0.0 + + nuclide.reactions.append(ReactionTuple( + name, daughter, q_value, 1.0)) + + if any(mt in reactions_available for mt in [18, 19, 20, 21, 38]): + if parent in fpy_data: + q_value = reactions[parent][18] + nuclide.reactions.append( + ReactionTuple('fission', 0, q_value, 1.0)) + + if 'fission' not in depl_chain.react_to_ind: + depl_chain.react_to_ind['fission'] = reaction_index + reaction_index += 1 + else: + missing_fpy.append(parent) + + if parent in fpy_data: + fpy = fpy_data[parent] + + if fpy.energies is not None: + nuclide.yield_energies = fpy.energies + else: + nuclide.yield_energies = [0.0] + + for E, table in zip(nuclide.yield_energies, fpy.independent): + yield_replace = 0.0 + yields = defaultdict(float) + for product, y in table.items(): + # Handle fission products that have no decay data available + if product not in decay_data: + daughter = replace_missing(product, decay_data) + product = daughter + yield_replace += y.nominal_value + + yields[product] += y.nominal_value + + if yield_replace > 0.0: + missing_fp.append((parent, E, yield_replace)) + + nuclide.yield_data[E] = [] + for k in sorted(yields, key=_get_zai): + nuclide.yield_data[E].append((k, yields[k])) + + # Display warnings + if missing_daughter: + print('The following decay modes have daughters with no decay data:') + for mode in missing_daughter: + print(' {}'.format(mode)) + print('') + + if missing_rx_product: + print('The following reaction products have no decay data:') + for vals in missing_rx_product: + print('{} {} -> {}'.format(*vals)) + print('') + + if missing_fpy: + print('The following fissionable nuclides have no fission product yields:') + for parent in missing_fpy: + print(' ' + parent) + print('') + + if missing_fp: + print('The following nuclides have fission products with no decay data:') + for vals in missing_fp: + print(' {}, E={} eV (total yield={})'.format(*vals)) + + return depl_chain + + @classmethod + def xml_read(cls, filename): + """Reads a depletion chain XML file. + + Parameters + ---------- + filename : str + The path to the depletion chain XML file. + + Todo + ---- + Allow for branching on capture, etc. + """ + depl_chain = cls() + + # Load XML tree + try: + root = ET.parse(filename) + except: + if filename is None: + print("No chain specified, either manually or in environment variable OPENDEPLETE_CHAIN.") + else: + print('Decay chain "', filename, '" is invalid.') + raise + + reaction_index = 0 + for i, nuclide_elem in enumerate(root.findall('nuclide_table')): + nuc = Nuclide.xml_read(nuclide_elem) + depl_chain.nuclide_dict[nuc.name] = i + + # Check for reaction paths + for rx in nuc.reactions: + if rx.type not in depl_chain.react_to_ind: + depl_chain.react_to_ind[rx.type] = reaction_index + reaction_index += 1 + + depl_chain.nuclides.append(nuc) + + return depl_chain + + def xml_write(self, filename): + """Writes a depletion chain XML file. + + Parameters + ---------- + filename : str + The path to the depletion chain XML file. + + """ + + root_elem = ET.Element('depletion') + for nuclide in self.nuclides: + root_elem.append(nuclide.xml_write()) + + tree = ET.ElementTree(root_elem) + if _have_lxml: + tree.write(filename, encoding='utf-8', pretty_print=True) + else: + clean_xml_indentation(root_elem, spaces_per_level=2) + tree.write(filename, encoding='utf-8') + + def form_matrix(self, rates): + """ Forms depletion matrix. + + Parameters + ---------- + rates : numpy.ndarray + 2D array indexed by nuclide then by cell. + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing depletion. + """ + + matrix = defaultdict(float) + reactions = set() + + for i, nuc in enumerate(self.nuclides): + + if nuc.n_decay_modes != 0: + # Decay paths + # Loss + decay_constant = math.log(2) / nuc.half_life + + if decay_constant != 0.0: + matrix[i, i] -= decay_constant + + # Gain + for _, target, branching_ratio in nuc.decay_modes: + # Allow for total annihilation for debug purposes + if target != 'Nothing': + branch_val = branching_ratio * decay_constant + + if branch_val != 0.0: + k = self.nuclide_dict[target] + matrix[k, i] += branch_val + + if nuc.name in self.nuc_to_react_ind: + # Extract all reactions for this nuclide in this cell + nuc_ind = self.nuc_to_react_ind[nuc.name] + nuc_rates = rates[nuc_ind, :] + + for r_type, target, _, br in nuc.reactions: + # Extract reaction index, and then final reaction rate + r_id = self.react_to_ind[r_type] + path_rate = nuc_rates[r_id] + + # Loss term -- make sure we only count loss once for + # reactions with branching ratios + if r_type not in reactions: + reactions.add(r_type) + if path_rate != 0.0: + matrix[i, i] -= path_rate + + # Gain term; allow for total annihilation for debug purposes + if target != 'Nothing': + if r_type != 'fission': + if path_rate != 0.0: + k = self.nuclide_dict[target] + matrix[k, i] += path_rate * br + else: + # Assume that we should always use thermal fission + # yields. At some point it would be nice to account + # for the energy-dependence.. + energy, data = sorted(nuc.yield_data.items())[0] + for product, y in data: + yield_val = y * path_rate + if yield_val != 0.0: + k = self.nuclide_dict[product] + matrix[k, i] += yield_val + + # Clear set of reactions + reactions.clear() + + # Use DOK matrix as intermediate representation, then convert to CSR and return + matrix_dok = sp.dok_matrix((self.n_nuclides, self.n_nuclides)) + dict.update(matrix_dok, matrix) + return matrix_dok.tocsr() + + def nuc_by_ind(self, ind): + """ Extracts nuclides from the list by dictionary key. + + Parameters + ---------- + ind : str + Name of nuclide. + + Returns + ------- + Nuclide + Nuclide object that corresponds to ind. + """ + return self.nuclides[self.nuclide_dict[ind]] diff --git a/openmc/deplete/dummy_comm.py b/openmc/deplete/dummy_comm.py new file mode 100644 index 0000000000..b3fa272648 --- /dev/null +++ b/openmc/deplete/dummy_comm.py @@ -0,0 +1,27 @@ +class DummyCommunicator(object): + rank = 0 + size = 1 + + def allgather(self, sendobj): + return [sendobj] + + def allreduce(self, sendobj, op=None): + return sendobj + + def barrier(self): + pass + + def bcast(self, obj, root=0): + return obj + + def gather(self, sendobj, root=0): + return [sendobj] + + def py2f(self): + return 0 + + def reduce(self, sendobj, op=None, root=0): + return sendobj + + def scatter(self, sendobj, root=0): + return sendobj[0] diff --git a/openmc/deplete/function.py b/openmc/deplete/function.py new file mode 100644 index 0000000000..74eb92422b --- /dev/null +++ b/openmc/deplete/function.py @@ -0,0 +1,114 @@ +"""function module. + +This module contains the Operator class, which is then passed to an integrator +to run a full depletion simulation. +""" + +from abc import ABCMeta, abstractmethod + +class Settings(object): + """ The Settings class. + + Contains all parameters necessary for the integrator. + + Attributes + ---------- + dt_vec : numpy.array + Array of time steps to take. + output_dir : str + Path to output directory to save results. + """ + + def __init__(self): + # Integrator specific + self.dt_vec = None + self.output_dir = None + +class Operator(metaclass=ABCMeta): + """ The Operator metaclass. + + This defines all functions that the integrator needs to operate. + + Attributes + ---------- + settings : Settings + Settings object. + """ + + def __init__(self, settings): + self.settings = settings + + @abstractmethod + def initial_condition(self): + """ Performs final setup and returns initial condition. + + Returns + ------- + list of numpy.array + Total density for initial conditions. + """ + + pass + + @abstractmethod + def eval(self, vec, print_out=True): + """ Runs a simulation. + + Parameters + ---------- + vec : list of numpy.array + Total atoms to be used in function. + print_out : bool, optional + Whether or not to print out time. + + Returns + ------- + k : float + Eigenvalue of the problem. + rates : ReactionRates + Reaction rates from this simulation. + seed : int + Seed for this simulation. + """ + + pass + + @abstractmethod + def get_results_info(self): + """ Returns volume list, cell lists, and nuc lists. + + Returns + ------- + volume : list of float + Volumes corresponding to materials in burn_list + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all cell IDs to be burned. Used for sorting the simulation. + full_burn_list : list of int + All burnable materials in the geometry. + """ + + pass + + @abstractmethod + def form_matrix(self, y, mat): + """ Forms the f(y) matrix in y' = f(y)y. + + Nominally a depletion matrix, this is abstracted on the off chance + that the function f has nothing to do with depletion at all. + + Parameters + ---------- + y : numpy.ndarray + An array representing y. + mat : int + Material id. + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing f(y). + """ + + pass diff --git a/openmc/deplete/integrator/__init__.py b/openmc/deplete/integrator/__init__.py new file mode 100644 index 0000000000..607650dc69 --- /dev/null +++ b/openmc/deplete/integrator/__init__.py @@ -0,0 +1,11 @@ +""" +Integrator +=========== + +The integrator subcomponents. +""" + +from .cecm import * +from .cram import * +from .predictor import * +from .save_results import * diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py new file mode 100644 index 0000000000..4d9baebb2e --- /dev/null +++ b/openmc/deplete/integrator/cecm.py @@ -0,0 +1,133 @@ +""" The CE/CM integrator.""" + +import copy +from itertools import repeat +import os +from multiprocessing import Pool +import time + +from .. import comm +from .cram import CRAM48, cram_wrapper +from .save_results import save_results + + +def cecm(operator, print_out=True): + """The CE/CM integrator. + + Implements the second order CE/CM Predictor-Corrector algorithm [ref]_. + This algorithm is mathematically defined as: + + .. math:: + y' &= A(y, t) y(t) + + A_p &= A(y_n, t_n) + + y_m &= \\text{expm}(A_p h/2) y_n + + A_c &= A(y_m, t_n + h/2) + + y_{n+1} &= \\text{expm}(A_c h) y_n + + .. [ref] + Isotalo, Aarno. "Comparison of Neutronics-Depletion Coupling Schemes + for Burnup Calculations—Continued Study." Nuclear Science and + Engineering 180.3 (2015): 286-300. + + Parameters + ---------- + operator : Operator + The operator object to simulate on. + print_out : bool, optional + Whether or not to print out time. + """ + + # Save current directory + dir_home = os.getcwd() + + # Move to folder + os.makedirs(operator.settings.output_dir, exist_ok=True) + os.chdir(operator.settings.output_dir) + + # Generate initial conditions + vec = operator.initial_condition() + + n_mats = len(vec) + + t = 0.0 + + for i, dt in enumerate(operator.settings.dt_vec): + # Create vectors + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] + + eigvl, rates, seed = operator.eval(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[0][i, :, :] for i in range(n_mats)) + dts = repeat(dt/2, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + x.append(x_result) + + eigvl, rates, seed = operator.eval(x[1]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[1][i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + + t += dt + vec = copy.deepcopy(x_result) + + # Perform one last simulation + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] + eigvl, rates, seed = operator.eval(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t], + len(operator.settings.dt_vec)) + + # Return to origin + os.chdir(dir_home) diff --git a/openmc/deplete/integrator/cram.py b/openmc/deplete/integrator/cram.py new file mode 100644 index 0000000000..a18d8450c3 --- /dev/null +++ b/openmc/deplete/integrator/cram.py @@ -0,0 +1,185 @@ +""" Chebyshev Rational Approximation Method module + +Implements two different forms of CRAM for use in opendeplete. +""" + +import numpy as np +import scipy.sparse as sp +import scipy.sparse.linalg as sla + + +def cram_wrapper(chain, n0, rates, dt): + """Wraps depletion matrix creation / CRAM solve for multiprocess execution + + Parameters + ---------- + chain : DepletionChain + Depletion chain used to construct the burnup matrix + n0 : numpy.array + Vector to operate a matrix exponent on. + rates : numpy.ndarray + 2D array indexed by nuclide then by cell. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + """ + A = chain.form_matrix(rates) + return CRAM48(A, n0, dt) + + +def CRAM16(A, n0, dt): + """ Chebyshev Rational Approximation Method, order 16 + + Algorithm is the 16th order Chebyshev Rational Approximation Method, + implemented in the more stable incomplete partial fraction (IPF) form + [cram16]_. + + .. [cram16] + Pusa, Maria. "Higher-Order Chebyshev Rational Approximation Method and + Application to Burnup Equations." Nuclear Science and Engineering 182.3 + (2016). + + Parameters + ---------- + A : scipy.linalg.csr_matrix + Matrix to take exponent of. + n0 : numpy.array + Vector to operate a matrix exponent on. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + """ + + alpha = np.array([+2.124853710495224e-16, + +5.464930576870210e+3 - 3.797983575308356e+4j, + +9.045112476907548e+1 - 1.115537522430261e+3j, + +2.344818070467641e+2 - 4.228020157070496e+2j, + +9.453304067358312e+1 - 2.951294291446048e+2j, + +7.283792954673409e+2 - 1.205646080220011e+5j, + +3.648229059594851e+1 - 1.155509621409682e+2j, + +2.547321630156819e+1 - 2.639500283021502e+1j, + +2.394538338734709e+1 - 5.650522971778156e+0j], + dtype=np.complex128) + theta = np.array([+0.0, + +3.509103608414918 + 8.436198985884374j, + +5.948152268951177 + 3.587457362018322j, + -5.264971343442647 + 16.22022147316793j, + +1.419375897185666 + 10.92536348449672j, + +6.416177699099435 + 1.194122393370139j, + +4.993174737717997 + 5.996881713603942j, + -1.413928462488886 + 13.49772569889275j, + -10.84391707869699 + 19.27744616718165j], + dtype=np.complex128) + + n = A.shape[0] + + alpha0 = 2.124853710495224e-16 + + k = 8 + + y = np.array(n0, dtype=np.float64) + for l in range(1, k+1): + y = 2.0*np.real(alpha[l]*sla.spsolve(A*dt - theta[l]*sp.eye(n), y)) + y + + y *= alpha0 + return y + + +def CRAM48(A, n0, dt): + """ Chebyshev Rational Approximation Method, order 48 + + Algorithm is the 48th order Chebyshev Rational Approximation Method, + implemented in the more stable incomplete partial fraction (IPF) form + [cram48]_. + + .. [cram48] + Pusa, Maria. "Higher-Order Chebyshev Rational Approximation Method and + Application to Burnup Equations." Nuclear Science and Engineering 182.3 + (2016). + + Parameters + ---------- + A : scipy.linalg.csr_matrix + Matrix to take exponent of. + n0 : numpy.array + Vector to operate a matrix exponent on. + dt : float + Time to integrate to. + + Returns + ------- + numpy.array + Results of the matrix exponent. + """ + + theta_r = np.array([-4.465731934165702e+1, -5.284616241568964e+0, + -8.867715667624458e+0, +3.493013124279215e+0, + +1.564102508858634e+1, +1.742097597385893e+1, + -2.834466755180654e+1, +1.661569367939544e+1, + +8.011836167974721e+0, -2.056267541998229e+0, + +1.449208170441839e+1, +1.853807176907916e+1, + +9.932562704505182e+0, -2.244223871767187e+1, + +8.590014121680897e-1, -1.286192925744479e+1, + +1.164596909542055e+1, +1.806076684783089e+1, + +5.870672154659249e+0, -3.542938819659747e+1, + +1.901323489060250e+1, +1.885508331552577e+1, + -1.734689708174982e+1, +1.316284237125190e+1]) + theta_i = np.array([+6.233225190695437e+1, +4.057499381311059e+1, + +4.325515754166724e+1, +3.281615453173585e+1, + +1.558061616372237e+1, +1.076629305714420e+1, + +5.492841024648724e+1, +1.316994930024688e+1, + +2.780232111309410e+1, +3.794824788914354e+1, + +1.799988210051809e+1, +5.974332563100539e+0, + +2.532823409972962e+1, +5.179633600312162e+1, + +3.536456194294350e+1, +4.600304902833652e+1, + +2.287153304140217e+1, +8.368200580099821e+0, + +3.029700159040121e+1, +5.834381701800013e+1, + +1.194282058271408e+0, +3.583428564427879e+0, + +4.883941101108207e+1, +2.042951874827759e+1]) + theta = np.array(theta_r + theta_i * 1j, dtype=np.complex128) + + alpha_r = np.array([+6.387380733878774e+2, +1.909896179065730e+2, + +4.236195226571914e+2, +4.645770595258726e+2, + +7.765163276752433e+2, +1.907115136768522e+3, + +2.909892685603256e+3, +1.944772206620450e+2, + +1.382799786972332e+5, +5.628442079602433e+3, + +2.151681283794220e+2, +1.324720240514420e+3, + +1.617548476343347e+4, +1.112729040439685e+2, + +1.074624783191125e+2, +8.835727765158191e+1, + +9.354078136054179e+1, +9.418142823531573e+1, + +1.040012390717851e+2, +6.861882624343235e+1, + +8.766654491283722e+1, +1.056007619389650e+2, + +7.738987569039419e+1, +1.041366366475571e+2]) + alpha_i = np.array([-6.743912502859256e+2, -3.973203432721332e+2, + -2.041233768918671e+3, -1.652917287299683e+3, + -1.783617639907328e+4, -5.887068595142284e+4, + -9.953255345514560e+3, -1.427131226068449e+3, + -3.256885197214938e+6, -2.924284515884309e+4, + -1.121774011188224e+3, -6.370088443140973e+4, + -1.008798413156542e+6, -8.837109731680418e+1, + -1.457246116408180e+2, -6.388286188419360e+1, + -2.195424319460237e+2, -6.719055740098035e+2, + -1.693747595553868e+2, -1.177598523430493e+1, + -4.596464999363902e+3, -1.738294585524067e+3, + -4.311715386228984e+1, -2.777743732451969e+2]) + alpha = np.array(alpha_r + alpha_i * 1j, dtype=np.complex128) + n = A.shape[0] + + alpha0 = 2.258038182743983e-47 + + k = 24 + + y = np.array(n0, dtype=np.float64) + for l in range(k): + y = 2.0*np.real(alpha[l]*sla.spsolve(A*dt - theta[l]*sp.eye(n), y)) + y + + y *= alpha0 + return y diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py new file mode 100644 index 0000000000..6c9d538fd6 --- /dev/null +++ b/openmc/deplete/integrator/predictor.py @@ -0,0 +1,100 @@ +""" The Predictor algorithm.""" + +import copy +from itertools import repeat +import os +from multiprocessing import Pool +import time + +from .. import comm +from .cram import CRAM48, cram_wrapper +from .save_results import save_results + + +def predictor(operator, print_out=True): + """The basic predictor integrator. + + Implements the first order predictor algorithm. This algorithm is + mathematically defined as: + + .. math:: + y' &= A(y, t) y(t) + + A_p &= A(y_n, t_n) + + y_{n+1} &= \\text{expm}(A_p h) y_n + + Parameters + ---------- + operator : Operator + The operator object to simulate on. + print_out : bool, optional + Whether or not to print out time. + """ + + # Save current directory + dir_home = os.getcwd() + + # Move to folder + os.makedirs(operator.settings.output_dir, exist_ok=True) + os.chdir(operator.settings.output_dir) + + # Generate initial conditions + vec = operator.initial_condition() + + n_mats = len(vec) + + t = 0.0 + + for i, dt in enumerate(operator.settings.dt_vec): + # Create vectors + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] + + eigvl, rates, seed = operator.eval(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[0][i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + t += dt + vec = copy.deepcopy(x_result) + + # Perform one last simulation + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] + eigvl, rates, seed = operator.eval(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t], + len(operator.settings.dt_vec)) + + # Return to origin + os.chdir(dir_home) diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py new file mode 100644 index 0000000000..35cbc7f3f1 --- /dev/null +++ b/openmc/deplete/integrator/save_results.py @@ -0,0 +1,46 @@ +""" Generic result saving code for integrators. + +""" +from opendeplete.results import Results, write_results + +def save_results(op, x, rates, eigvls, seeds, t, step_ind): + """ Creates and writes results to disk + + Parameters + ---------- + op : Function + The operator used to generate these results. + x : list of list of numpy.array + The prior x vectors. Indexed [i][cell] using the above equation. + rates : list of ReactionRates + The reaction rates for each substep. + eigvls : list of float + Eigenvalue for each substep + seeds : list of int + Seeds for each substep. + t : list of float + Time indices. + step_ind : int + Step index. + """ + + # Get indexing terms + vol_list, nuc_list, burn_list, full_burn_list = op.get_results_info() + + # Create results + stages = len(x) + results = Results() + results.allocate(vol_list, nuc_list, burn_list, full_burn_list, stages) + + n_mat = len(burn_list) + + for i in range(stages): + for mat_i in range(n_mat): + results[i, mat_i, :] = x[i][mat_i][:] + + results.k = eigvls + results.seeds = seeds + results.time = t + results.rates = rates + + write_results(results, "results.h5", step_ind) diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py new file mode 100644 index 0000000000..1208a9b3c3 --- /dev/null +++ b/openmc/deplete/nuclide.py @@ -0,0 +1,178 @@ +"""Nuclide module. + +Contains the per-nuclide components of a depletion chain. +""" + +from collections import namedtuple +try: + import lxml.etree as ET +except ImportError: + import xml.etree.ElementTree as ET + +DecayTuple = namedtuple('DecayTuple', 'type target branching_ratio') +ReactionTuple = namedtuple('ReactionTuple', 'type target Q branching_ratio') + + +class Nuclide(object): + """The Nuclide class. + + Contains everything in a depletion chain relating to a single nuclide. + + Attributes + ---------- + name : str + Name of nuclide. + half_life : float + Half life of nuclide in s^-1. + decay_energy : float + Energy deposited from decay in eV. + n_decay_modes : int + Number of decay pathways. + decay_modes : list of DecayTuple + Decay mode information. Each element of the list is a named tuple with + attributes 'type', 'target', and 'branching_ratio'. + n_reaction_paths : int + Number of possible reaction pathways. + reactions : list of ReactionTuple + Reaction information. Each element of the list is a named tuple with + attribute 'type', 'target', 'Q', and 'branching_ratio'. + yield_data : dict of float to list + Maps tabulated energy to list of (product, yield) for all + neutron-induced fission products. + yield_energies : list of float + Energies at which fission product yiels exist + + """ + + def __init__(self): + # Information about the nuclide + self.name = None + self.half_life = None + self.decay_energy = 0.0 + + # Decay paths + self.decay_modes = [] + + # Reaction paths + self.reactions = [] + + # Neutron fission yields, if present + self.yield_data = {} + self.yield_energies = [] + + @property + def n_decay_modes(self): + """Number of decay modes.""" + return len(self.decay_modes) + + @property + def n_reaction_paths(self): + """Number of possible reaction pathways.""" + return len(self.reactions) + + @classmethod + def xml_read(cls, element): + """Read nuclide from an XML element. + + Parameters + ---------- + element : xml.etree.ElementTree.Element + XML element to write nuclide data to + + Returns + ------- + nuc : Nuclide + Instance of a nuclide + + """ + nuc = cls() + nuc.name = element.get('name') + + # Check for half-life + if 'half_life' in element.attrib: + nuc.half_life = float(element.get('half_life')) + nuc.decay_energy = float(element.get('decay_energy', '0')) + + # Check for decay paths + for decay_elem in element.iter('decay_type'): + d_type = decay_elem.get('type') + target = decay_elem.get('target') + branching_ratio = float(decay_elem.get('branching_ratio')) + nuc.decay_modes.append(DecayTuple(d_type, target, branching_ratio)) + + # Check for reaction paths + for reaction_elem in element.iter('reaction_type'): + r_type = reaction_elem.get('type') + Q = float(reaction_elem.get('Q', '0')) + branching_ratio = float(reaction_elem.get('branching_ratio', '1')) + + # If the type is not fission, get target and Q value, otherwise + # just set null values + if r_type != 'fission': + target = reaction_elem.get('target') + else: + target = None + + # Append reaction + nuc.reactions.append(ReactionTuple( + r_type, target, Q, branching_ratio)) + + fpy_elem = element.find('neutron_fission_yields') + if fpy_elem is not None: + for yields_elem in fpy_elem.iter('fission_yields'): + E = float(yields_elem.get('energy')) + products = yields_elem.find('products').text.split() + yields = [float(y) for y in + yields_elem.find('data').text.split()] + nuc.yield_data[E] = list(zip(products, yields)) + nuc.yield_energies = list(sorted(nuc.yield_data.keys())) + + return nuc + + def xml_write(self): + """Write nuclide to XML element. + + Returns + ------- + elem : xml.etree.ElementTree.Element + XML element to write nuclide data to + + """ + elem = ET.Element('nuclide_table') + elem.set('name', self.name) + + if self.half_life is not None: + elem.set('half_life', str(self.half_life)) + elem.set('decay_modes', str(len(self.decay_modes))) + elem.set('decay_energy', str(self.decay_energy)) + for mode, daughter, br in self.decay_modes: + mode_elem = ET.SubElement(elem, 'decay_type') + mode_elem.set('type', mode) + mode_elem.set('target', daughter) + mode_elem.set('branching_ratio', str(br)) + + elem.set('reactions', str(len(self.reactions))) + for rx, daughter, Q, br in self.reactions: + rx_elem = ET.SubElement(elem, 'reaction_type') + rx_elem.set('type', rx) + rx_elem.set('Q', str(Q)) + if rx != 'fission': + rx_elem.set('target', daughter) + if br != 1.0: + rx_elem.set('branching_ratio', str(br)) + + if self.yield_data: + fpy_elem = ET.SubElement(elem, 'neutron_fission_yields') + energy_elem = ET.SubElement(fpy_elem, 'energies') + energy_elem.text = ' '.join(str(E) for E in self.yield_energies) + + for E in self.yield_energies: + yields_elem = ET.SubElement(fpy_elem, 'fission_yields') + yields_elem.set('energy', str(E)) + + products_elem = ET.SubElement(yields_elem, 'products') + products_elem.text = ' '.join(x[0] for x in self.yield_data[E]) + data_elem = ET.SubElement(yields_elem, 'data') + data_elem.text = ' '.join(str(x[1]) for x in self.yield_data[E]) + + return elem diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py new file mode 100644 index 0000000000..347dc71857 --- /dev/null +++ b/openmc/deplete/openmc_wrapper.py @@ -0,0 +1,853 @@ +""" The OpenMC wrapper module. + +This module implements the OpenDeplete -> OpenMC linkage. +""" + +import copy +from collections import OrderedDict +import os +import random +import sys +import time +try: + import lxml.etree as ET + _have_lxml = True +except ImportError: + import xml.etree.ElementTree as ET + from openmc.clean_xml import clean_xml_indentation + _have_lxml = False + +import h5py +import numpy as np +import openmc +import openmc.capi + +from . import comm +from .atom_number import AtomNumber +from .depletion_chain import DepletionChain +from .reaction_rates import ReactionRates +from .function import Settings, Operator + + +_JOULE_PER_EV = 1.6021766208e-19 + + +def chunks(items, n): + min_size, extra = divmod(len(items), n) + j = 0 + chunk_list = [] + for i in range(n): + chunk_size = min_size + int(i < extra) + chunk_list.append(items[j:j + chunk_size]) + j += chunk_size + return chunk_list + + +class OpenMCSettings(Settings): + """The OpenMCSettings class. + + Extends Settings to provide information OpenMC needs to run. + + Attributes + ---------- + dt_vec : numpy.array + Array of time steps to take. (From Settings) + tol : float + Tolerance for adaptive time stepping. (From Settings) + output_dir : str + Path to output directory to save results. (From Settings) + chain_file : str + Path to the depletion chain xml file. Defaults to the environment + variable "OPENDEPLETE_CHAIN" if it exists. + openmc_call : str + OpenMC executable path. Defaults to "openmc". + particles : int + Number of particles to simulate per batch. + batches : int + Number of batches. + inactive : int + Number of inactive batches. + lower_left : list of float + Coordinate of lower left of bounding box of geometry. + upper_right : list of float + Coordinate of upper right of bounding box of geometry. + entropy_dimension : list of int + Grid size of entropy. + dilute_initial : float, default 1.0e3 + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. + round_number : bool + Whether or not to round output to OpenMC to 8 digits. + Useful in testing, as OpenMC is incredibly sensitive to exact values. + constant_seed : int + If present, all runs will be performed with this seed. + power : float + Power of the reactor in W. For a 2D problem, the power can be given in + W/cm as long as the "volume" assigned to a depletion material is + actually an area in cm^2. + """ + + def __init__(self): + super().__init__() + # OpenMC specific + try: + self.chain_file = os.environ["OPENDEPLETE_CHAIN"] + except KeyError: + self.chain_file = None + self.openmc_call = "openmc" + self.particles = None + self.batches = None + self.inactive = None + self.lower_left = None + self.upper_right = None + self.entropy_dimension = None + self.dilute_initial = 1.0e3 + + # OpenMC testing specific + self.round_number = False + self.constant_seed = None + + # Depletion problem specific + self.power = None + + +class Materials(object): + """The Materials class. + + Contains information about cross sections for a cell. + + Attributes + ---------- + temperature : float + Temperature in Kelvin for each region. + sab : str or list of str + ENDF S(a,b) name for a region that needs S(a,b) data. Not set if no + S(a,b) needed for region. + """ + + def __init__(self): + self.temperature = None + self.sab = None + + +class OpenMCOperator(Operator): + """The OpenMC Operator class. + + Provides Operator functions for OpenMC. + + Parameters + ---------- + geometry : openmc.Geometry + The OpenMC geometry object. + settings : OpenMCSettings + Settings object. + + Attributes + ---------- + settings : OpenMCSettings + Settings object. (From Operator) + geometry : openmc.Geometry + The OpenMC geometry object. + materials : list of Materials + Materials to be used for this simulation. + seed : int + The RNG seed used in last OpenMC run. + number : AtomNumber + Total number of atoms in simulation. + participating_nuclides : set of str + A set listing all unique nuclides available from cross_sections.xml. + chain : DepletionChain + The depletion chain information necessary to form matrices and tallies. + reaction_rates : ReactionRates + Reaction rates from the last operator step. + power : OrderedDict of str to float + Material-by-Material power. Indexed by material ID. + mat_name : OrderedDict of str to int + The name of region each material is set to. Indexed by material ID. + burn_mat_to_id : OrderedDict of str to int + Dictionary mapping material ID (as a string) to an index in reaction_rates. + burn_nuc_to_id : OrderedDict of str to int + Dictionary mapping nuclide name (as a string) to an index in + reaction_rates. + n_nuc : int + Number of nuclides considered in the decay chain. + mat_tally_ind : OrderedDict of str to int + Dictionary mapping material ID to index in tally. + """ + + def __init__(self, geometry, settings): + super().__init__(settings) + + self.geometry = geometry + self.seed = 0 + self.number = None + self.participating_nuclides = None + self.reaction_rates = None + self.power = None + self.mat_name = OrderedDict() + self.burn_mat_to_ind = OrderedDict() + self.burn_nuc_to_ind = None + + # Read depletion chain + self.chain = DepletionChain.xml_read(settings.chain_file) + + # Clear out OpenMC, create task lists, distribute + if comm.rank == 0: + clean_up_openmc() + mat_burn_list, mat_not_burn_list, volume, self.mat_tally_ind, \ + nuc_dict = self.extract_mat_ids() + else: + # Dummy variables + mat_burn_list = None + mat_not_burn_list = None + volume = None + nuc_dict = None + self.mat_tally_ind = None + + mat_burn = comm.scatter(mat_burn_list) + mat_not_burn = comm.scatter(mat_not_burn_list) + nuc_dict = comm.bcast(nuc_dict) + volume = comm.bcast(volume) + self.mat_tally_ind = comm.bcast(self.mat_tally_ind) + + # Load participating nuclides + self.load_participating() + + # Extract number densities from the geometry + self.extract_number(mat_burn, mat_not_burn, volume, nuc_dict) + + # Create reaction rate tables + self.initialize_reaction_rates() + + def __del__(self): + openmc.capi.finalize() + + def extract_mat_ids(self): + """ Extracts materials and assigns them to processes. + + Returns + ------- + mat_burn_lists : list of list of int + List of burnable materials indexed by rank. + mat_not_burn_lists : list of list of int + List of non-burnable materials indexed by rank. + volume : OrderedDict of str to float + Volume of each cell + mat_tally_ind : OrderedDict of str to int + Dictionary mapping material ID to index in tally. + nuc_dict : OrderedDict of str to int + Nuclides in order of how they'll appear in the simulation. + """ + + mat_burn = set() + mat_not_burn = set() + nuc_set = set() + + volume = OrderedDict() + + # Iterate once through the geometry to get dictionaries + cells = self.geometry.get_all_material_cells() + for cell in cells.values(): + name = cell.name + + if isinstance(cell.fill, openmc.Material): + mat = cell.fill + for nuclide in mat.get_nuclide_densities(): + nuc_set.add(nuclide) + if mat.depletable: + mat_burn.add(str(mat.id)) + volume[str(mat.id)] = mat.volume + else: + mat_not_burn.add(str(mat.id)) + self.mat_name[mat.id] = name + else: + for mat in cell.fill: + for nuclide in mat.get_nuclide_densities(): + nuc_set.add(nuclide) + if mat.depletable: + mat_burn.add(str(mat.id)) + volume[str(mat.id)] = mat.volume + else: + mat_not_burn.add(str(mat.id)) + self.mat_name[mat.id] = name + + need_vol = [] + + for mat_id in volume: + if volume[mat_id] is None: + need_vol.append(mat_id) + + if need_vol: + exit("Need volumes for materials: " + str(need_vol)) + + # Sort the sets + mat_burn = sorted(mat_burn, key=int) + mat_not_burn = sorted(mat_not_burn, key=int) + nuc_set = sorted(nuc_set) + + # Construct a global nuclide dictionary, burned first + nuc_dict = copy.deepcopy(self.chain.nuclide_dict) + + i = len(nuc_dict) + + for nuc in nuc_set: + if nuc not in nuc_dict: + nuc_dict[nuc] = i + i += 1 + + # Decompose geometry + mat_burn_lists = chunks(mat_burn, comm.size) + mat_not_burn_lists = chunks(mat_not_burn, comm.size) + + mat_tally_ind = OrderedDict() + + for i, mat in enumerate(mat_burn): + mat_tally_ind[mat] = i + + return mat_burn_lists, mat_not_burn_lists, volume, mat_tally_ind, nuc_dict + + def extract_number(self, mat_burn, mat_not_burn, volume, nuc_dict): + """ Construct self.number read from geometry + + Parameters + ---------- + mat_burn : list of int + Materials to be burned managed by this thread. + mat_not_burn + Materials not to be burned managed by this thread. + volume : OrderedDict of str to float + Volumes for the above materials. + nuc_dict : OrderedDict of str to int + Nuclides to be used in the simulation. + """ + + # Same with materials + mat_dict = OrderedDict() + self.burn_mat_to_ind = OrderedDict() + i = 0 + for mat in mat_burn: + mat_dict[mat] = i + self.burn_mat_to_ind[mat] = i + i += 1 + + for mat in mat_not_burn: + mat_dict[mat] = i + i += 1 + + n_mat_burn = len(mat_burn) + n_nuc_burn = len(self.chain.nuclide_dict) + + self.number = AtomNumber(mat_dict, nuc_dict, volume, n_mat_burn, n_nuc_burn) + + if self.settings.dilute_initial != 0.0: + for nuc in self.burn_nuc_to_ind: + self.number.set_atom_density(np.s_[:], nuc, self.settings.dilute_initial) + + # Now extract the number densities and store + cells = self.geometry.get_all_material_cells() + for cell in cells.values(): + if isinstance(cell.fill, openmc.Material): + if str(cell.fill.id) in mat_dict: + self.set_number_from_mat(cell.fill) + else: + for mat in cell.fill: + if str(mat.id) in mat_dict: + self.set_number_from_mat(mat) + + def set_number_from_mat(self, mat): + """ Extracts material and number densities from openmc.Material + + Parameters + ---------- + mat : openmc.Materials + The material to read from + """ + + mat_id = str(mat.id) + mat_ind = self.number.mat_to_ind[mat_id] + + nuc_dens = mat.get_nuclide_atom_densities() + for nuclide in nuc_dens: + name = nuclide.name + number = nuc_dens[nuclide][1] * 1.0e24 + self.number.set_atom_density(mat_id, name, number) + + def initialize_reaction_rates(self): + """ Create reaction rates object. """ + self.reaction_rates = ReactionRates( + self.burn_mat_to_ind, + self.burn_nuc_to_ind, + self.chain.react_to_ind) + + self.chain.nuc_to_react_ind = self.burn_nuc_to_ind + + def eval(self, vec, print_out=True): + """ Runs a simulation. + + Parameters + ---------- + vec : list of numpy.array + Total atoms to be used in function. + print_out : bool, optional + Whether or not to print out time. + + Returns + ------- + mat : list of scipy.sparse.csr_matrix + Matrices for the next step. + k : float + Eigenvalue of the problem. + rates : ReactionRates + Reaction rates from this simulation. + seed : int + Seed for this simulation. + """ + + # Prevent OpenMC from complaining about re-creating tallies + clean_up_openmc() + + # Update status + self.set_density(vec) + + time_start = time.time() + + # Update material compositions and tally nuclides + self._update_materials() + openmc.capi.tallies[1].nuclides = self._get_tally_nuclides() + + # Run OpenMC + openmc.capi.reset() + openmc.capi.run() + + time_openmc = time.time() + + # Extract results + k = self.unpack_tallies_and_normalize() + + if comm.rank == 0: + time_unpack = time.time() + + if print_out: + print("Time to openmc: ", time_openmc - time_start) + print("Time to unpack: ", time_unpack - time_openmc) + + return k, copy.deepcopy(self.reaction_rates), self.seed + + def form_matrix(self, y, mat): + """ Forms the depletion matrix. + + Parameters + ---------- + y : numpy.ndarray + An array representing reaction rates for this cell. + mat : int + Material id. + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing the depletion matrix. + """ + + return copy.deepcopy(self.chain.form_matrix(y[mat, :, :])) + + def initial_condition(self): + """ Performs final setup and returns initial condition. + + Returns + ------- + list of numpy.array + Total density for initial conditions. + """ + + # Create XML files + if comm.rank == 0: + self.geometry.export_to_xml() + self.generate_settings_xml() + self.generate_materials_xml() + + # Initialize OpenMC library + comm.barrier() + openmc.capi.init(comm) + + # Generate tallies in memory + self.generate_tallies() + + # Return number density vector + return self.total_density_list() + + def _update_materials(self): + """Updates material compositions in OpenMC on all processes.""" + + for rank in range(comm.size): + number_i = comm.bcast(self.number, root=rank) + + for mat in number_i.mat_to_ind: + nuclides = [] + densities = [] + for nuc in number_i.nuc_to_ind: + if nuc in self.participating_nuclides: + val = 1.0e-24 * number_i.get_atom_density(mat, nuc) + + # If nuclide is zero, do not add to the problem. + if val > 0.0: + if self.settings.round_number: + val_magnitude = np.floor(np.log10(val)) + val_scaled = val / 10**val_magnitude + val_round = round(val_scaled, 8) + + val = val_round * 10**val_magnitude + + nuclides.append(nuc) + densities.append(val) + else: + # Only output warnings if values are significantly + # negative. CRAM does not guarantee positive values. + if val < -1.0e-21: + print("WARNING: nuclide ", nuc, " in material ", mat, + " is negative (density = ", val, " at/barn-cm)") + number_i[mat, nuc] = 0.0 + + mat_internal = openmc.capi.materials[int(mat)] + mat_internal.set_densities(nuclides, densities) + + def generate_materials_xml(self): + """ Creates materials.xml from self.number. + + Due to uncertainty with how MPI interacts with OpenMC API, this + constructs the XML manually. The long term goal is to do this + through direct memory writing. + """ + + materials = openmc.Materials(self.geometry.get_all_materials() + .values()) + + # Sort nuclides according to order in AtomNumber object + nuclides = list(self.number.nuc_to_ind.keys()) + for mat in materials: + mat._nuclides.sort(key=lambda x: nuclides.index(x[0])) + + materials.export_to_xml() + + def generate_settings_xml(self): + """ Generates settings.xml. + + This function creates settings.xml using the value of the settings + variable. + + Todo + ---- + Rewrite to generalize source box. + """ + + batches = self.settings.batches + inactive = self.settings.inactive + particles = self.settings.particles + + # Just a generic settings file to get it running. + settings_file = openmc.Settings() + settings_file.batches = batches + settings_file.inactive = inactive + settings_file.particles = particles + settings_file.source = openmc.Source(space=openmc.stats.Box( + self.settings.lower_left, self.settings.upper_right)) + + if self.settings.entropy_dimension is not None: + entropy_mesh = openmc.Mesh() + entropy_mesh.lower_left = self.settings.lower_left + entropy_mesh.upper_right = self.settings.upper_right + entropy_mesh.dimension = self.settings.entropy_dimension + settings_file.entropy_mesh = entropy_mesh + + # Set seed + if self.settings.constant_seed is not None: + seed = self.settings.constant_seed + else: + seed = random.randint(1, sys.maxsize-1) + + settings_file.seed = self.seed = seed + + settings_file.export_to_xml() + + def _get_tally_nuclides(self): + nuc_set = set() + + # Create the set of all nuclides in the decay chain in cells marked for + # burning in which the number density is greater than zero. + for nuc in self.number.nuc_to_ind: + if nuc in self.participating_nuclides: + if np.sum(self.number[:, nuc]) > 0.0: + nuc_set.add(nuc) + + # Communicate which nuclides have nonzeros to rank 0 + if comm.rank == 0: + for i in range(1, comm.size): + nuc_newset = comm.recv(source=i, tag=i) + nuc_set |= nuc_newset + + else: + comm.send(nuc_set, dest=0, tag=comm.rank) + + if comm.rank == 0: + # Sort nuclides in the same order as self.number + nuc_list = [nuc for nuc in self.number.nuc_to_ind + if nuc in nuc_set] + else: + nuc_list = None + + # Store list of tally nuclides on each process + nuc_list = comm.bcast(nuc_list, root=0) + tally_nuclides = [nuc for nuc in nuc_list + if nuc in self.chain.nuclide_dict] + + return tally_nuclides + + def generate_tallies(self): + """Generates depletion tallies. + + Using information from self.depletion_chain as well as the nuclides + currently in the problem, this function automatically generates a + tally.xml for the simulation. + """ + + # Create tallies for depleting regions + materials = [openmc.capi.materials[int(i)] + for i in self.mat_tally_ind] + mat_filter = openmc.capi.MaterialFilter(materials, 1) + + # Set up a tally that has a material filter covering each depletable + # material and scores corresponding to all reactions that cause + # transmutation. The nuclides for the tally are set later when eval() is + # called. + tally_dep = openmc.capi.Tally(1) + tally_dep.scores = self.chain.react_to_ind.keys() + tally_dep.filters = [mat_filter] + + def total_density_list(self): + """ Returns a list of total density lists. + + This list is in the exact same order as depletion_matrix_list, so that + matrix exponentiation can be done easily. + + Returns + ------- + list of numpy.array + A list of np.arrays containing total atoms of each cell. + """ + + total_density = [self.number.get_mat_slice(i) for i in range(self.number.n_mat_burn)] + + return total_density + + def set_density(self, total_density): + """ Sets density. + + Sets the density in the exact same order as total_density_list outputs, + allowing for internal consistency + + Parameters + ---------- + total_density : list of numpy.array + Total atoms. + """ + + # Fill in values + for i in range(self.number.n_mat_burn): + self.number.set_mat_slice(i, total_density[i]) + + def unpack_tallies_and_normalize(self): + """ Unpack tallies from OpenMC + + This function reads the tallies generated by OpenMC (from the tally.xml + file generated in generate_tally_xml) normalizes them so that the total + power generated is new_power, and then stores them in the reaction rate + database. + + Returns + ------- + k : float + Eigenvalue of the last simulation. + + Todo + ---- + Provide units for power + """ + + rates = self.reaction_rates + rates[:, :, :] = 0.0 + + k_combined = openmc.capi.keff()[0] + + # Extract tally bins + materials = list(self.mat_tally_ind.keys()) + nuclides = openmc.capi.tallies[1].nuclides + reactions = list(self.chain.react_to_ind.keys()) + + # Form fast map + nuc_ind = [rates.nuc_to_ind[nuc] for nuc in nuclides] + react_ind = [rates.react_to_ind[react] for react in reactions] + + # Compute fission power + # TODO : improve this calculation + + # Keep track of energy produced from all reactions in eV per source + # particle + energy = 0.0 + + # Create arrays to store fission Q values, reaction rates, and nuclide + # numbers + fission_Q = np.zeros(rates.n_nuc) + rates_expanded = np.zeros((rates.n_nuc, rates.n_react)) + number = np.zeros(rates.n_nuc) + + fission_ind = rates.react_to_ind["fission"] + + for nuclide in self.chain.nuclides: + if nuclide.name in rates.nuc_to_ind: + for rx in nuclide.reactions: + if rx.type == 'fission': + ind = rates.nuc_to_ind[nuclide.name] + fission_Q[ind] = rx.Q + break + + # Extract results + for i, mat in enumerate(self.number.burn_mat_list): + # Get tally index + slab = materials.index(mat) + + # Get material results hyperslab + results = openmc.capi.tallies[1].results[slab, :, 1] + + # Zero out reaction rates and nuclide numbers + rates_expanded[:] = 0.0 + number[:] = 0.0 + + # Expand into our memory layout + j = 0 + for nuc, i_nuc_results in zip(nuclides, nuc_ind): + number[i_nuc_results] = self.number[mat, nuc] + for react in react_ind: + rates_expanded[i_nuc_results, react] = results[j] + j += 1 + + # Accumulate energy from fission + energy += np.dot(rates_expanded[:, fission_ind], fission_Q) + + # Divide by total number and store + for i_nuc_results in nuc_ind: + if number[i_nuc_results] != 0.0: + for react in react_ind: + rates_expanded[i_nuc_results, react] /= number[i_nuc_results] + + rates.rates[i, :, :] = rates_expanded + + # Reduce energy produced from all processes + energy = comm.allreduce(energy) + + # Determine power in eV/s + power = self.settings.power / _JOULE_PER_EV + + # Scale reaction rates to obtain units of reactions/sec + rates[:, :, :] *= power / energy + + return k_combined + + def load_participating(self): + """ Loads a cross_sections.xml file to find participating nuclides. + + This allows for nuclides that are important in the decay chain but not + important neutronically, or have no cross section data. + """ + + # Reads cross_sections.xml to create a dictionary containing + # participating (burning and not just decaying) nuclides. + + try: + filename = os.environ["OPENMC_CROSS_SECTIONS"] + except KeyError: + filename = None + + self.participating_nuclides = set() + + try: + tree = ET.parse(filename) + except: + if filename is None: + msg = "No cross_sections.xml specified in materials." + else: + msg = 'Cross section file "{}" is invalid.'.format(filename) + raise IOError(msg) + + root = tree.getroot() + self.burn_nuc_to_ind = OrderedDict() + nuc_ind = 0 + + for nuclide_node in root.findall('library'): + mats = nuclide_node.get('materials') + if not mats: + continue + for name in mats.split(): + # Make a burn list of the union of nuclides in cross_sections.xml + # and nuclides in depletion chain. + if name not in self.participating_nuclides: + self.participating_nuclides.add(name) + if name in self.chain.nuclide_dict: + self.burn_nuc_to_ind[name] = nuc_ind + nuc_ind += 1 + + @property + def n_nuc(self): + """Number of nuclides considered in the decay chain.""" + return len(self.chain.nuclides) + + def get_results_info(self): + """ Returns volume list, cell lists, and nuc lists. + + Returns + ------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all cell IDs to be burned. Used for sorting the simulation. + full_burn_dict : OrderedDict of str to int + Maps cell name to index in global geometry. + """ + + nuc_list = self.number.burn_nuc_list + burn_list = self.number.burn_mat_list + + volume = {} + for i, mat in enumerate(burn_list): + volume[mat] = self.number.volume[i] + + # Combine volume dictionaries across processes + volume_list = comm.allgather(volume) + volume = {k: v for d in volume_list for k, v in d.items()} + + return volume, nuc_list, burn_list, self.mat_tally_ind + +def density_to_mat(dens_dict): + """ Generates an OpenMC material from a cell ID and self.number_density. + Parameters + ---------- + m_id : int + Cell ID. + Returns + ------- + openmc.Material + The OpenMC material filled with nuclides. + """ + + mat = openmc.Material() + for key in dens_dict: + mat.add_nuclide(key, 1.0e-24*dens_dict[key]) + mat.set_density('sum') + + return mat + +def clean_up_openmc(): + """ Resets all automatic indexing in OpenMC, as these get in the way. """ + openmc.reset_auto_ids() diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py new file mode 100644 index 0000000000..7b934027a5 --- /dev/null +++ b/openmc/deplete/reaction_rates.py @@ -0,0 +1,113 @@ +"""ReactionRates module. + +An ndarray to store reaction rates with string, integer, or slice indexing. +""" + +import numpy as np + + +class ReactionRates(object): + """ ReactionRates class. + + An ndarray to store reaction rates with string, integer, or slice indexing. + + Parameters + ---------- + mat_to_ind : OrderedDict of str to int + A dictionary mapping material ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + react_to_ind : OrderedDict of str to int + A dictionary mapping reaction name as string to index. + + Attributes + ---------- + mat_to_ind : OrderedDict of str to int + A dictionary mapping cell ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + react_to_ind : OrderedDict of str to int + A dictionary mapping reaction name as string to index. + n_mat : int + Number of materials. + n_nuc : int + Number of nucs. + n_react : int + Number of reactions. + rates : numpy.array + Array storing rates indexed by the above dictionaries. + """ + + def __init__(self, mat_to_ind, nuc_to_ind, react_to_ind): + + self.mat_to_ind = mat_to_ind + self.nuc_to_ind = nuc_to_ind + self.react_to_ind = react_to_ind + + self.rates = np.zeros((self.n_mat, self.n_nuc, self.n_react)) + + def __getitem__(self, pos): + """ Retrieves an item from reaction_rates. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a material index, a nuc index, and a + reaction index. These indexes can be strings (which get converted + to integers via the dictionaries), integers used directly, or + slices. + + Returns + ------- + numpy.array + The value indexed from self.rates. + """ + + mat, nuc, react = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + if isinstance(react, str): + react = self.react_to_ind[react] + + return self.rates[mat, nuc, react] + + def __setitem__(self, pos, val): + """ Sets an item from reaction_rates. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a material index, a nuc index, and a + reaction index. These indexes can be strings (which get converted + to integers via the dictionaries), integers used directly, or + slices. + val : float + The value to set the array to. + """ + + mat, nuc, react = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + if isinstance(react, str): + react = self.react_to_ind[react] + + self.rates[mat, nuc, react] = val + + @property + def n_mat(self): + """Number of cells.""" + return len(self.mat_to_ind) + + @property + def n_nuc(self): + """Number of nucs.""" + return len(self.nuc_to_ind) + + @property + def n_react(self): + """Number of reactions.""" + return len(self.react_to_ind) diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py new file mode 100644 index 0000000000..c0ec1627ea --- /dev/null +++ b/openmc/deplete/results.py @@ -0,0 +1,454 @@ +""" The results module. + +Contains results generation and saving capabilities. +""" + +from collections import OrderedDict +import copy + +import numpy as np +import h5py + +from . import comm, have_mpi +from .reaction_rates import ReactionRates + +RESULTS_VERSION = 2 + +class Results(object): + """ Contains output of opendeplete. + + Attributes + ---------- + k : list of float + Eigenvalue for each substep. + seeds : list of int + Seeds for each substep. + time : list of float + Time at beginning, end of step, in seconds. + n_mat : int + Number of mats. + n_nuc : int + Number of nuclides. + rates : list of ReactionRates + The reaction rates for each substep. + volume : OrderedDict of int to float + Dictionary mapping mat id to volume. + mat_to_ind : OrderedDict of str to int + A dictionary mapping mat ID as string to index. + nuc_to_ind : OrderedDict of str to int + A dictionary mapping nuclide name as string to index. + mat_to_hdf5_ind : OrderedDict of str to int + A dictionary mapping mat ID as string to global index. + n_hdf5_mats : int + Number of materials in entire geometry. + n_stages : int + Number of stages in simulation. + data : numpy.array + Atom quantity, stored by stage, mat, then by nuclide. + """ + + def __init__(self): + self.k = None + self.seeds = None + self.time = None + self.p_terms = None + self.rates = None + self.volume = None + + self.mat_to_ind = None + self.nuc_to_ind = None + self.mat_to_hdf5_ind = None + + self.data = None + + def allocate(self, volume, nuc_list, burn_list, full_burn_dict, stages): + """ Allocates memory of Results. + + Parameters + ---------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all mat IDs to be burned. Used for sorting the simulation. + full_burn_dict : dict of str to int + Map of material name to id in global geometry. + stages : int + Number of stages in simulation. + """ + + self.volume = copy.deepcopy(volume) + self.nuc_to_ind = OrderedDict() + self.mat_to_ind = OrderedDict() + self.mat_to_hdf5_ind = copy.deepcopy(full_burn_dict) + + for i, mat in enumerate(burn_list): + self.mat_to_ind[mat] = i + + for i, nuc in enumerate(nuc_list): + self.nuc_to_ind[nuc] = i + + # Create storage array + self.data = np.zeros((stages, self.n_mat, self.n_nuc)) + + @property + def n_mat(self): + """Number of mats.""" + return len(self.mat_to_ind) + + @property + def n_nuc(self): + """Number of nuclides.""" + return len(self.nuc_to_ind) + + @property + def n_hdf5_mats(self): + """Number of materials in entire geometry.""" + return len(self.mat_to_hdf5_ind) + + @property + def n_stages(self): + """Number of stages in simulation.""" + return self.data.shape[0] + + def __getitem__(self, pos): + """ Retrieves an item from results. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a stage index, mat index and a nuc + index. All can be integers or slices. The second two can be + strings corresponding to their respective dictionary. + + Returns + ------- + float + The atoms for stage, mat, nuc + """ + + stage, mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + return self.data[stage, mat, nuc] + + def __setitem__(self, pos, val): + """ Sets an item from results. + + Parameters + ---------- + pos : tuple + A three-length tuple containing a stage index, mat index and a nuc + index. All can be integers or slices. The second two can be + strings corresponding to their respective dictionary. + + val : float + The value to set data to. + """ + + stage, mat, nuc = pos + if isinstance(mat, str): + mat = self.mat_to_ind[mat] + if isinstance(nuc, str): + nuc = self.nuc_to_ind[nuc] + + self.data[stage, mat, nuc] = val + + def create_hdf5(self, handle): + """ Creates file structure for a blank HDF5 file. + + Parameters + ---------- + handle : h5py.File or h5py.Group + An hdf5 file or group type to store this in. + """ + + # Create and save the 5 dictionaries: + # quantities + # self.mat_to_ind -> self.volume (TODO: support for changing volumes) + # self.nuc_to_ind + # reactions + # self.rates[0].nuc_to_ind (can be different from above, above is superset) + # self.rates[0].react_to_ind + # these are shared by every step of the simulation, and should be deduplicated. + + # Store concentration mat and nuclide dictionaries (along with volumes) + + handle.create_dataset("version", data=RESULTS_VERSION) + + mat_int = sorted([int(mat) for mat in self.mat_to_hdf5_ind]) + mat_list = [str(mat) for mat in mat_int] + nuc_list = sorted(self.nuc_to_ind.keys()) + rxn_list = sorted(self.rates[0].react_to_ind.keys()) + + n_mats = self.n_hdf5_mats + n_nuc_number = len(nuc_list) + n_nuc_rxn = len(self.rates[0].nuc_to_ind) + n_rxn = len(rxn_list) + n_stages = self.n_stages + + mat_group = handle.create_group("cells") + + for mat in mat_list: + mat_single_group = mat_group.create_group(mat) + mat_single_group.attrs["index"] = self.mat_to_hdf5_ind[mat] + mat_single_group.attrs["volume"] = self.volume[mat] + + nuc_group = handle.create_group("nuclides") + + for nuc in nuc_list: + nuc_single_group = nuc_group.create_group(nuc) + nuc_single_group.attrs["atom number index"] = self.nuc_to_ind[nuc] + if nuc in self.rates[0].nuc_to_ind: + nuc_single_group.attrs["reaction rate index"] = self.rates[0].nuc_to_ind[nuc] + + rxn_group = handle.create_group("reactions") + + for rxn in rxn_list: + rxn_single_group = rxn_group.create_group(rxn) + rxn_single_group.attrs["index"] = self.rates[0].react_to_ind[rxn] + + # Construct array storage + + handle.create_dataset("number", (1, n_stages, n_mats, n_nuc_number), + maxshape=(None, n_stages, n_mats, n_nuc_number), + chunks=(1, 1, n_mats, n_nuc_number), + dtype='float64') + + handle.create_dataset("reaction rates", (1, n_stages, n_mats, n_nuc_rxn, n_rxn), + maxshape=(None, n_stages, n_mats, n_nuc_rxn, n_rxn), + chunks=(1, 1, n_mats, n_nuc_rxn, n_rxn), + dtype='float64') + + handle.create_dataset("eigenvalues", (1, n_stages), + maxshape=(None, n_stages), dtype='float64') + + handle.create_dataset("seeds", (1, n_stages), maxshape=(None, n_stages), dtype='int64') + + handle.create_dataset("time", (1, 2), maxshape=(None, 2), dtype='float64') + + def to_hdf5(self, handle, index): + """ Converts results object into an hdf5 object. + + Parameters + ---------- + handle : h5py.File or h5py.Group + An hdf5 file or group type to store this in. + index : int + What step is this? + """ + + if "/number" not in handle: + comm.barrier() + self.create_hdf5(handle) + + comm.barrier() + + # Grab handles + number_dset = handle["/number"] + rxn_dset = handle["/reaction rates"] + eigenvalues_dset = handle["/eigenvalues"] + seeds_dset = handle["/seeds"] + time_dset = handle["/time"] + + # Get number of results stored + number_shape = list(number_dset.shape) + number_results = number_shape[0] + + new_shape = index + 1 + + if number_results < new_shape: + # Extend first dimension by 1 + number_shape[0] = new_shape + number_dset.resize(number_shape) + + rxn_shape = list(rxn_dset.shape) + rxn_shape[0] = new_shape + rxn_dset.resize(rxn_shape) + + eigenvalues_shape = list(eigenvalues_dset.shape) + eigenvalues_shape[0] = new_shape + eigenvalues_dset.resize(eigenvalues_shape) + + seeds_shape = list(seeds_dset.shape) + seeds_shape[0] = new_shape + seeds_dset.resize(seeds_shape) + + time_shape = list(time_dset.shape) + time_shape[0] = new_shape + time_dset.resize(time_shape) + + # If nothing to write, just return + if len(self.mat_to_ind) == 0: + return + + # Add data + # Note, for the last step, self.n_stages = 1, even if n_stages != 1. + n_stages = self.n_stages + inds = [self.mat_to_hdf5_ind[mat] for mat in self.mat_to_ind] + low = min(inds) + high = max(inds) + for i in range(n_stages): + number_dset[index, i, low:high+1, :] = self.data[i, :, :] + rxn_dset[index, i, low:high+1, :, :] = self.rates[i][:, :, :] + if comm.rank == 0: + eigenvalues_dset[index, i] = self.k[i] + seeds_dset[index, i] = self.seeds[i] + if comm.rank == 0: + time_dset[index, :] = self.time + + def from_hdf5(self, handle, index): + """ Loads results object from HDF5. + + Parameters + ---------- + handle : h5py.File or h5py.Group + An hdf5 file or group type to load from. + index : int + What step is this? + """ + + # Grab handles + number_dset = handle["/number"] + eigenvalues_dset = handle["/eigenvalues"] + seeds_dset = handle["/seeds"] + time_dset = handle["/time"] + + self.data = number_dset[index, :, :, :] + self.k = eigenvalues_dset[index, :] + self.seeds = seeds_dset[index, :] + self.time = time_dset[index, :] + + # Reconstruct dictionaries + self.volume = OrderedDict() + self.mat_to_ind = OrderedDict() + self.nuc_to_ind = OrderedDict() + rxn_nuc_to_ind = OrderedDict() + rxn_to_ind = OrderedDict() + + for mat in handle["/cells"]: + mat_handle = handle["/cells/" + mat] + vol = mat_handle.attrs["volume"] + ind = mat_handle.attrs["index"] + + self.volume[mat] = vol + self.mat_to_ind[mat] = ind + + for nuc in handle["/nuclides"]: + nuc_handle = handle["/nuclides/" + nuc] + ind_atom = nuc_handle.attrs["atom number index"] + self.nuc_to_ind[nuc] = ind_atom + + if "reaction rate index" in nuc_handle.attrs: + rxn_nuc_to_ind[nuc] = nuc_handle.attrs["reaction rate index"] + + for rxn in handle["/reactions"]: + rxn_handle = handle["/reactions/" + rxn] + rxn_to_ind[rxn] = rxn_handle.attrs["index"] + + self.rates = [] + # Reconstruct reactions + for i in range(self.n_stages): + rate = ReactionRates(self.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) + + rate.rates = handle["/reaction rates"][index, i, :, :, :] + self.rates.append(rate) + + +def get_dict(number): + """ Given an operator nested dictionary, output indexing dictionaries. + + These indexing dictionaries map mat IDs and nuclide names to indices + inside of Results.data. + + Parameters + ---------- + number : AtomNumber + The object to extract dictionaries from + + Returns + ------- + mat_to_ind : OrderedDict of str to int + Maps mat strings to index in array. + nuc_to_ind : OrderedDict of str to int + Maps nuclide strings to index in array. + """ + mat_to_ind = OrderedDict() + nuc_to_ind = OrderedDict() + + for nuc in number.nuc_to_ind: + nuc_ind = number.nuc_to_ind[nuc] + if nuc_ind < number.n_nuc_burn: + nuc_to_ind[nuc] = nuc_ind + + for mat in number.mat_to_ind: + mat_ind = number.mat_to_ind[mat] + if mat_ind < number.n_mat_burn: + mat_to_ind[mat] = mat_ind + + return mat_to_ind, nuc_to_ind + + +def write_results(result, filename, index): + """ Outputs result to an .hdf5 file. + + Parameters + ---------- + result : Results + Object to be stored in a file. + filename : String + Target filename. + index : int + What step is this? + """ + + if have_mpi and h5py.get_config().mpi: + kwargs = {'driver': 'mpio', 'comm': comm} + else: + kwargs = {} + + kwargs['mode'] = "w" if index == 0 else "a" + + with h5py.File(filename, **kwargs) as handle: + result.to_hdf5(handle, index) + + +def read_results(filename): + """ Reads out a list of results objects from an hdf5 file. + + Parameters + ---------- + filename : str + The filename to read from. + + Returns + ------- + results : list of Results + The result objects. + """ + + file = h5py.File(filename, "r") + + assert file["/version"].value == RESULTS_VERSION + + # Grab handles + number_dset = file["/number"] + + # Get number of results stored + number_shape = list(number_dset.shape) + number_results = number_shape[0] + + results = [] + + for i in range(number_results): + result = Results() + result.from_hdf5(file, i) + results.append(result) + + file.close() + + return results diff --git a/openmc/deplete/utilities.py b/openmc/deplete/utilities.py new file mode 100644 index 0000000000..54632ed9c2 --- /dev/null +++ b/openmc/deplete/utilities.py @@ -0,0 +1,98 @@ +""" The utilities module. + +Contains functions that can be used to post-process objects that come out of +the results module. +""" + +import numpy as np + +def evaluate_single_nuclide(results, cell, nuc): + """ Evaluates a single nuclide in a single cell from a results list. + + Parameters + ---------- + results : list of results + The results to extract data from. Must be sorted and continuous. + cell : str + Cell name to evaluate + nuc : str + Nuclide name to evaluate + + Returns + ------- + time : numpy.array + Time vector. + concentration : numpy.array + Total number of atoms in the cell. + """ + + n_points = len(results) + time = np.zeros(n_points) + concentration = np.zeros(n_points) + + # Evaluate value in each region + for i, result in enumerate(results): + time[i] = result.time[0] + concentration[i] = result[0, cell, nuc] + + return time, concentration + +def evaluate_reaction_rate(results, cell, nuc, rxn): + """ Evaluates a single nuclide reaction rate in a single cell from a results list. + + Parameters + ---------- + results : list of Results + The results to extract data from. Must be sorted and continuous. + cell : str + Cell name to evaluate + nuc : str + Nuclide name to evaluate + rxn : str + Reaction rate to evaluate + + Returns + ------- + time : numpy.array + Time vector. + rate : numpy.array + Reaction rate. + """ + + n_points = len(results) + time = np.zeros(n_points) + rate = np.zeros(n_points) + # Evaluate value in each region + for i, result in enumerate(results): + time[i] = result.time[0] + rate[i] = result.rates[0][cell, nuc, rxn] * result[0, cell, nuc] + + return time, rate + +def evaluate_eigenvalue(results): + """ Evaluates the eigenvalue from a results list. + + Parameters + ---------- + results : list of Results + The results to extract data from. Must be sorted and continuous. + + Returns + ------- + time : numpy.array + Time vector. + eigenvalue : numpy.array + Eigenvalue. + """ + + n_points = len(results) + time = np.zeros(n_points) + eigenvalue = np.zeros(n_points) + + # Evaluate value in each region + for i, result in enumerate(results): + + time[i] = result.time[0] + eigenvalue[i] = result.k[0] + + return time, eigenvalue diff --git a/scripts/example_geometry.py b/scripts/example_geometry.py new file mode 100644 index 0000000000..9afcc0d464 --- /dev/null +++ b/scripts/example_geometry.py @@ -0,0 +1,358 @@ +"""An example file showing how to make a geometry. + +This particular example creates a 3x3 geometry, with 8 regular pins and one +Gd-157 2 wt-percent enriched. All pins are segmented. +""" + +from collections import OrderedDict +import math + +import numpy as np +import openmc + +from opendeplete import density_to_mat + + +def generate_initial_number_density(): + """ Generates initial number density. + + These results were from a CASMO5 run in which the gadolinium pin was + loaded with 2 wt percent of Gd-157. + """ + + # Concentration to be used for all fuel pins + fuel_dict = OrderedDict() + fuel_dict['U235'] = 1.05692e21 + fuel_dict['U234'] = 1.00506e19 + fuel_dict['U238'] = 2.21371e22 + fuel_dict['O16'] = 4.62954e22 + fuel_dict['O17'] = 1.127684e20 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + fuel_dict['Gd156'] = 1.0e10 + fuel_dict['Gd157'] = 1.0e10 + # fuel_dict['O18'] = 9.51352e19 # Does not exist in ENDF71, merged into 17 + + # Concentration to be used for the gadolinium fuel pin + fuel_gd_dict = OrderedDict() + fuel_gd_dict['U235'] = 1.03579e21 + fuel_gd_dict['U238'] = 2.16943e22 + fuel_gd_dict['Gd156'] = 3.95517E+10 + fuel_gd_dict['Gd157'] = 1.08156e20 + fuel_gd_dict['O16'] = 4.64035e22 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + # There are a whole bunch of 1e-10 stuff here. + + # Concentration to be used for cladding + clad_dict = OrderedDict() + clad_dict['O16'] = 3.07427e20 + clad_dict['O17'] = 7.48868e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Fe54'] = 5.57350e18 + clad_dict['Fe56'] = 8.74921e19 + clad_dict['Fe57'] = 2.02057e18 + clad_dict['Fe58'] = 2.68901e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Ni58'] = 2.51631e19 + clad_dict['Ni60'] = 9.69278e18 + clad_dict['Ni61'] = 4.21338e17 + clad_dict['Ni62'] = 1.34341e18 + clad_dict['Ni64'] = 3.43127e17 + clad_dict['Zr90'] = 2.18320e22 + clad_dict['Zr91'] = 4.76104e21 + clad_dict['Zr92'] = 7.27734e21 + clad_dict['Zr94'] = 7.37494e21 + clad_dict['Zr96'] = 1.18814e21 + clad_dict['Sn112'] = 4.67352e18 + clad_dict['Sn114'] = 3.17992e18 + clad_dict['Sn115'] = 1.63814e18 + clad_dict['Sn116'] = 7.00546e19 + clad_dict['Sn117'] = 3.70027e19 + clad_dict['Sn118'] = 1.16694e20 + clad_dict['Sn119'] = 4.13872e19 + clad_dict['Sn120'] = 1.56973e20 + clad_dict['Sn122'] = 2.23076e19 + clad_dict['Sn124'] = 2.78966e19 + + # Gap concentration + # Funny enough, the example problem uses air. + gap_dict = OrderedDict() + gap_dict['O16'] = 7.86548e18 + gap_dict['O17'] = 2.99548e15 + gap_dict['N14'] = 3.38646e19 + gap_dict['N15'] = 1.23717e17 + + # Concentration to be used for coolant + # No boron + cool_dict = OrderedDict() + cool_dict['H1'] = 4.68063e22 + cool_dict['O16'] = 2.33427e22 + cool_dict['O17'] = 8.89086e18 + + # Store these dictionaries in the initial conditions dictionary + initial_density = OrderedDict() + initial_density['fuel_gd'] = fuel_gd_dict + initial_density['fuel'] = fuel_dict + initial_density['gap'] = gap_dict + initial_density['clad'] = clad_dict + initial_density['cool'] = cool_dict + + # Set up libraries to use + temperature = OrderedDict() + sab = OrderedDict() + + # Toggle betweeen MCNP and NNDC data + MCNP = False + + if MCNP: + temperature['fuel_gd'] = 900.0 + temperature['fuel'] = 900.0 + # We approximate temperature of everything as 600K, even though it was + # actually 580K. + temperature['gap'] = 600.0 + temperature['clad'] = 600.0 + temperature['cool'] = 600.0 + else: + temperature['fuel_gd'] = 293.6 + temperature['fuel'] = 293.6 + temperature['gap'] = 293.6 + temperature['clad'] = 293.6 + temperature['cool'] = 293.6 + + sab['cool'] = 'c_H_in_H2O' + + # Set up burnable materials + burn = OrderedDict() + burn['fuel_gd'] = True + burn['fuel'] = True + burn['gap'] = False + burn['clad'] = False + burn['cool'] = False + + return temperature, sab, initial_density, burn + +def segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad): + """ Calculates a segmented pin. + + Separates a pin with n_rings and n_wedges. All cells have equal volume. + Pin is centered at origin. + """ + + # Calculate all the volumes of interest + v_fuel = math.pi * r_fuel**2 + v_gap = math.pi * r_gap**2 - v_fuel + v_clad = math.pi * r_clad**2 - v_fuel - v_gap + v_ring = v_fuel / n_rings + v_segment = v_ring / n_wedges + + # Compute ring radiuses + r_rings = np.zeros(n_rings) + + for i in range(n_rings): + r_rings[i] = math.sqrt(1.0/(math.pi) * v_ring * (i+1)) + + # Compute thetas + theta = np.linspace(0, 2*math.pi, n_wedges + 1) + + # Compute surfaces + fuel_rings = [openmc.ZCylinder(x0=0, y0=0, R=r_rings[i]) + for i in range(n_rings)] + + fuel_wedges = [openmc.Plane(A=math.cos(theta[i]), B=math.sin(theta[i])) + for i in range(n_wedges)] + + gap_ring = openmc.ZCylinder(x0=0, y0=0, R=r_gap) + clad_ring = openmc.ZCylinder(x0=0, y0=0, R=r_clad) + + # Create cells + fuel_cells = [] + if n_wedges == 1: + for i in range(n_rings): + cell = openmc.Cell(name='fuel') + if i == 0: + cell.region = -fuel_rings[0] + else: + cell.region = +fuel_rings[i-1] & -fuel_rings[i] + fuel_cells.append(cell) + else: + for i in range(n_rings): + for j in range(n_wedges): + cell = openmc.Cell(name='fuel') + if i == 0: + if j != n_wedges-1: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[0]) + else: + if j != n_wedges-1: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[0]) + fuel_cells.append(cell) + + # Gap ring + gap_cell = openmc.Cell(name='gap') + gap_cell.region = +fuel_rings[-1] & -gap_ring + fuel_cells.append(gap_cell) + + # Clad ring + clad_cell = openmc.Cell(name='clad') + clad_cell.region = +gap_ring & -clad_ring + fuel_cells.append(clad_cell) + + # Moderator + mod_cell = openmc.Cell(name='cool') + mod_cell.region = +clad_ring + fuel_cells.append(mod_cell) + + # Form universe + fuel_u = openmc.Universe() + fuel_u.add_cells(fuel_cells) + + return fuel_u, v_segment, v_gap, v_clad + +def generate_geometry(n_rings, n_wedges): + """ Generates example geometry. + + This function creates the initial geometry, a 9 pin reflective problem. + One pin, containing gadolinium, is discretized into sectors. + + In addition to what one would do with the general OpenMC geometry code, it + is necessary to create a dictionary, volume, that maps a cell ID to a + volume. Further, by naming cells the same as the above materials, the code + can automatically handle the mapping. + + Parameters + ---------- + n_rings : int + Number of rings to generate for the geometry + n_wedges : int + Number of wedges to generate for the geometry + """ + + pitch = 1.26197 + r_fuel = 0.412275 + r_gap = 0.418987 + r_clad = 0.476121 + + n_pin = 3 + + # This table describes the 'fuel' to actual type mapping + # It's not necessary to do it this way. Just adjust the initial conditions + # below. + mapping = ['fuel', 'fuel', 'fuel', + 'fuel', 'fuel_gd', 'fuel', + 'fuel', 'fuel', 'fuel'] + + # Form pin cell + fuel_u, v_segment, v_gap, v_clad = segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad) + + # Form lattice + all_water_c = openmc.Cell(name='cool') + all_water_u = openmc.Universe(cells=(all_water_c, )) + + lattice = openmc.RectLattice() + lattice.pitch = [pitch]*2 + lattice.lower_left = [-pitch*n_pin/2, -pitch*n_pin/2] + lattice_array = [[fuel_u for i in range(n_pin)] for j in range(n_pin)] + lattice.universes = lattice_array + lattice.outer = all_water_u + + # Bound universe + x_low = openmc.XPlane(x0=-pitch*n_pin/2, boundary_type='reflective') + x_high = openmc.XPlane(x0=pitch*n_pin/2, boundary_type='reflective') + y_low = openmc.YPlane(y0=-pitch*n_pin/2, boundary_type='reflective') + y_high = openmc.YPlane(y0=pitch*n_pin/2, boundary_type='reflective') + z_low = openmc.ZPlane(z0=-10, boundary_type='reflective') + z_high = openmc.ZPlane(z0=10, boundary_type='reflective') + + # Compute bounding box + lower_left = [-pitch*n_pin/2, -pitch*n_pin/2, -10] + upper_right = [pitch*n_pin/2, pitch*n_pin/2, 10] + + root_c = openmc.Cell(fill=lattice) + root_c.region = (+x_low & -x_high + & +y_low & -y_high + & +z_low & -z_high) + root_u = openmc.Universe(universe_id=0, cells=(root_c, )) + geometry = openmc.Geometry(root_u) + + v_cool = pitch**2 - (v_gap + v_clad + n_rings * n_wedges * v_segment) + + # Store volumes for later usage + volume = {'fuel': v_segment, 'gap':v_gap, 'clad':v_clad, 'cool':v_cool} + + return geometry, volume, mapping, lower_left, upper_right + +def generate_problem(n_rings=5, n_wedges=8): + """ Merges geometry and materials. + + This function initializes the materials for each cell using the dictionaries + provided by generate_initial_number_density. It is assumed a cell named + 'fuel' will have further region differentiation (see mapping). + + Parameters + ---------- + n_rings : int, optional + Number of rings to generate for the geometry + n_wedges : int, optional + Number of wedges to generate for the geometry + """ + + # Get materials dictionary, geometry, and volumes + temperature, sab, initial_density, burn = generate_initial_number_density() + geometry, volume, mapping, lower_left, upper_right = generate_geometry(n_rings, n_wedges) + + # Apply distribmats, fill geometry + cells = geometry.root_universe.get_all_cells() + for cell_id in cells: + cell = cells[cell_id] + if cell.name == 'fuel': + + omc_mats = [] + + for cell_type in mapping: + omc_mat = density_to_mat(initial_density[cell_type]) + + if cell_type in sab: + omc_mat.add_s_alpha_beta(sab[cell_type]) + omc_mat.temperature = temperature[cell_type] + omc_mat.depletable = burn[cell_type] + omc_mat.volume = volume['fuel'] + + omc_mats.append(omc_mat) + + cell.fill = omc_mats + elif cell.name != '': + omc_mat = density_to_mat(initial_density[cell.name]) + + if cell.name in sab: + omc_mat.add_s_alpha_beta(sab[cell.name]) + omc_mat.temperature = temperature[cell.name] + omc_mat.depletable = burn[cell.name] + omc_mat.volume = volume[cell.name] + + cell.fill = omc_mat + + return geometry, lower_left, upper_right diff --git a/scripts/example_plot.py b/scripts/example_plot.py new file mode 100644 index 0000000000..d2c6ee9d6a --- /dev/null +++ b/scripts/example_plot.py @@ -0,0 +1,46 @@ +"""An example file showing how to plot data from a simulation.""" + +import matplotlib.pyplot as plt + +from opendeplete import read_results, \ + evaluate_single_nuclide, \ + evaluate_reaction_rate, \ + evaluate_eigenvalue + +# Set variables for where the data is, and what we want to read out. +result_folder = "test" + +# Load data +results = read_results(result_folder + "/results.h5") + +cell = "5" +nuc = "Gd157" +rxn = "(n,gamma)" + +# Total number of nuclides +plt.figure() +# Pointwise data +x, y = evaluate_single_nuclide(results, cell, nuc) +plt.semilogy(x, y) + +plt.xlabel("Time, s") +plt.ylabel("Total Number") +plt.savefig("number.pdf") + +# Reaction rate +plt.figure() +x, y = evaluate_reaction_rate(results, cell, nuc, rxn) +plt.plot(x, y) +plt.xlabel("Time, s") +plt.ylabel("Reaction Rate, 1/s") + +plt.savefig("rate.pdf") + +# Eigenvalue +plt.figure() +x, y = evaluate_eigenvalue(results) +plt.plot(x, y) +plt.xlabel("Time, s") +plt.ylabel("Eigenvalue") + +plt.savefig("eigvl.pdf") diff --git a/scripts/example_run.py b/scripts/example_run.py new file mode 100644 index 0000000000..bb80f65820 --- /dev/null +++ b/scripts/example_run.py @@ -0,0 +1,39 @@ +"""An example file showing how to run a simulation.""" + +import numpy as np +import opendeplete + +import example_geometry + +# Load geometry from example +geometry, lower_left, upper_right = example_geometry.generate_problem() + +# Create dt vector for 5.5 months with 15 day timesteps +dt1 = 15*24*60*60 # 15 days +dt2 = 5.5*30*24*60*60 # 5.5 months +N = np.floor(dt2/dt1) + +dt = np.repeat([dt1], N) + +# Create settings variable +settings = opendeplete.OpenMCSettings() + +settings.openmc_call = "openmc" +# An example for mpiexec: +# settings.openmc_call = ["mpiexec", "openmc"] +settings.particles = 1000 +settings.batches = 100 +settings.inactive = 40 +settings.lower_left = lower_left +settings.upper_right = upper_right +settings.entropy_dimension = [10, 10, 1] + +joule_per_mev = 1.6021766208e-13 +settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO +settings.dt_vec = dt +settings.output_dir = 'test' + +op = opendeplete.OpenMCOperator(geometry, settings) + +# Perform simulation using the MCNPX/MCNP6 algorithm +opendeplete.integrator.cecm(op) diff --git a/scripts/make_chain.py b/scripts/make_chain.py new file mode 100644 index 0000000000..2e0d9d3bc4 --- /dev/null +++ b/scripts/make_chain.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +import glob +import os +from zipfile import ZipFile + +import requests +from tqdm import tqdm +import opendeplete + + +urls = [ + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-neutrons.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-decay.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-nfy.zip' +] + + +def download_file(url): + response = requests.get(url, stream=True) + filesize = int(response.headers.get('content-length')) + + # Check if file already downloaded + basename = url.split('/')[-1] + if os.path.exists(basename): + if os.path.getsize(basename) == filesize: + return basename + else: + overwrite = input('Overwrite {}? ([y]/n) '.format(basename)) + if overwrite.lower().startswith('n'): + return basename + + with open(basename, 'wb') as f: + with tqdm(desc='Downloading {}'.format(basename), + total=filesize, unit='B', unit_scale=True) as pbar: + for i, chunk in enumerate(response.iter_content(chunk_size=4096)): + pbar.update(4096) + if chunk: + f.write(chunk) + + return basename + + +def main(): + for url in urls: + basename = download_file(url) + with ZipFile(basename, 'r') as zf: + print('Extracting {}...'.format(basename)) + zf.extractall() + + decay_files = glob.glob(os.path.join('decay', '*.endf')) + nfy_files = glob.glob(os.path.join('nfy', '*.endf')) + neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) + + chain = opendeplete.DepletionChain.from_endf(decay_files, nfy_files, neutron_files) + chain.xml_write('chain_endfb71.xml') + + +if __name__ == '__main__': + main() diff --git a/tests/deplete_tests/__init__.py b/tests/deplete_tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/deplete_tests/dummy_geometry.py b/tests/deplete_tests/dummy_geometry.py new file mode 100644 index 0000000000..6101519411 --- /dev/null +++ b/tests/deplete_tests/dummy_geometry.py @@ -0,0 +1,165 @@ +""" The OpenMC wrapper module. + +This module implements the OpenDeplete -> OpenMC linkage. +""" + +import numpy as np +import scipy.sparse as sp + +from opendeplete.reaction_rates import ReactionRates +from opendeplete.function import Operator + +class DummyGeometry(Operator): + """ This is a dummy geometry class with no statistical uncertainty. + + y_1' = sin(y_2) y_1 + cos(y_1) y_2 + y_2' = -cos(y_2) y_1 + sin(y_1) y_2 + + y_1(0) = 1 + y_2(0) = 1 + + y_1(1.5) ~ 2.3197067076743316 + y_2(1.5) ~ 3.1726475740397628 + + """ + + def __init__(self, settings): + Operator.__init__(self, settings) + + @property + def chain(self): + return self + + def eval(self, vec, print_out=False): + """ Evaluates F(y) + + Parameters + ---------- + vec : list of numpy.array + Total atoms to be used in function. + print_out : bool, optional, ignored + Whether or not to print out time. + + Returns + ------- + k : float + Zero. + rates : ReactionRates + Reaction rates from this simulation. + seed : int + Zero. + """ + + cell_to_ind = {"1" : 0} + nuc_to_ind = {"1" : 0, "2" : 1} + react_to_ind = {"1" : 0} + + reaction_rates = ReactionRates(cell_to_ind, nuc_to_ind, react_to_ind) + + reaction_rates[0, 0, 0] = vec[0][0] + reaction_rates[0, 1, 0] = vec[0][1] + + # Create a fake rates object + + return 0.0, reaction_rates, 0 + + def form_matrix(self, rates): + """ Forms the f(y) matrix in y' = f(y)y. + + Nominally a depletion matrix, this is abstracted on the off chance + that the function f has nothing to do with depletion at all. + + Parameters + ---------- + rates : numpy.ndarray + Slice of reaction rates for a single material + + Returns + ------- + scipy.sparse.csr_matrix + Sparse matrix representing f(y). + """ + + y_1 = rates[0, 0] + y_2 = rates[1, 0] + + mat = np.zeros((2, 2)) + a11 = np.sin(y_2) + a12 = np.cos(y_1) + a21 = -np.cos(y_2) + a22 = np.sin(y_1) + + return sp.csr_matrix(np.array([[a11, a12], [a21, a22]])) + + @property + def volume(self): + """ + volume : dict of str float + Volumes of material + """ + + return {"1": 0.0} + + @property + def nuc_list(self): + """ + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + """ + + return ["1", "2"] + + @property + def burn_list(self): + """ + burn_list : list of str + A list of all cell IDs to be burned. Used for sorting the simulation. + """ + + return ["1"] + + @property + def mat_tally_ind(self): + """Maps cell name to index in global geometry.""" + return {"1": 0} + + + @property + def reaction_rates(self): + """ + reaction_rates : ReactionRates + Reaction rates from the last operator step. + """ + cell_to_ind = {"1" : 0} + nuc_to_ind = {"1" : 0, "2" : 1} + react_to_ind = {"1" : 0} + + return ReactionRates(cell_to_ind, nuc_to_ind, react_to_ind) + + def initial_condition(self): + """ Returns initial vector. + + Returns + ------- + list of numpy.array + Total density for initial conditions. + """ + + return [np.array((1.0, 1.0))] + + def get_results_info(self): + """ Returns volume list, cell lists, and nuc lists. + + Returns + ------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all cell IDs to be burned. Used for sorting the simulation. + full_burn_dict : OrderedDict of str to int + Maps cell name to index in global geometry. + """ + + return self.volume, self.nuc_list, self.burn_list, self.mat_tally_ind diff --git a/tests/deplete_tests/example_geometry.py b/tests/deplete_tests/example_geometry.py new file mode 120000 index 0000000000..1071aabc05 --- /dev/null +++ b/tests/deplete_tests/example_geometry.py @@ -0,0 +1 @@ +../../scripts/example_geometry.py \ No newline at end of file diff --git a/tests/deplete_tests/test_atom_number.py b/tests/deplete_tests/test_atom_number.py new file mode 100644 index 0000000000..9a17230f86 --- /dev/null +++ b/tests/deplete_tests/test_atom_number.py @@ -0,0 +1,180 @@ +""" Tests for atom_number.py. """ + +import unittest + +import numpy as np + +from opendeplete import atom_number + +class TestAtomNumber(unittest.TestCase): + """ Tests for the AtomNumber class. """ + + def test_indexing(self): + """Tests the __getitem__ and __setitem__ routines simultaneously.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number["10000", "U238"] = 1.0 + number["10001", "U238"] = 2.0 + number["10000", "U235"] = 3.0 + number["10001", "U235"] = 4.0 + + # String indexing + self.assertEqual(number["10000", "U238"], 1.0) + self.assertEqual(number["10001", "U238"], 2.0) + self.assertEqual(number["10000", "U235"], 3.0) + self.assertEqual(number["10001", "U235"], 4.0) + + # Int indexing + self.assertEqual(number[0, 0], 1.0) + self.assertEqual(number[1, 0], 2.0) + self.assertEqual(number[0, 1], 3.0) + self.assertEqual(number[1, 1], 4.0) + + number[0, 0] = 5.0 + + self.assertEqual(number[0, 0], 5.0) + self.assertEqual(number["10000", "U238"], 5.0) + + def test_n_mat(self): + """ Test number of materials property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + self.assertEqual(number.n_mat, 2) + + def test_n_nuc(self): + """ Test number of nuclides property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + self.assertEqual(number.n_nuc, 3) + + def test_burn_nuc_list(self): + """ Test the list of burned nuclides property """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + self.assertEqual(number.burn_nuc_list, ["U238", "U235"]) + + def test_burn_mat_list(self): + """ Test the list of burned nuclides property """ + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + self.assertEqual(number.burn_mat_list, ["10000", "10001"]) + + def test_density_indexing(self): + """Tests the get and set_atom_density routines simultaneously.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.set_atom_density("10000", "U238", 1.0) + number.set_atom_density("10001", "U238", 2.0) + number.set_atom_density("10002", "U238", 3.0) + number.set_atom_density("10000", "U235", 4.0) + number.set_atom_density("10001", "U235", 5.0) + number.set_atom_density("10002", "U235", 6.0) + number.set_atom_density("10000", "U234", 7.0) + number.set_atom_density("10001", "U234", 8.0) + number.set_atom_density("10002", "U234", 9.0) + + # String indexing + self.assertEqual(number.get_atom_density("10000", "U238"), 1.0) + self.assertEqual(number.get_atom_density("10001", "U238"), 2.0) + self.assertEqual(number.get_atom_density("10002", "U238"), 3.0) + self.assertEqual(number.get_atom_density("10000", "U235"), 4.0) + self.assertEqual(number.get_atom_density("10001", "U235"), 5.0) + self.assertEqual(number.get_atom_density("10002", "U235"), 6.0) + self.assertEqual(number.get_atom_density("10000", "U234"), 7.0) + self.assertEqual(number.get_atom_density("10001", "U234"), 8.0) + self.assertEqual(number.get_atom_density("10002", "U234"), 9.0) + + # Int indexing + self.assertEqual(number.get_atom_density(0, 0), 1.0) + self.assertEqual(number.get_atom_density(1, 0), 2.0) + self.assertEqual(number.get_atom_density(2, 0), 3.0) + self.assertEqual(number.get_atom_density(0, 1), 4.0) + self.assertEqual(number.get_atom_density(1, 1), 5.0) + self.assertEqual(number.get_atom_density(2, 1), 6.0) + self.assertEqual(number.get_atom_density(0, 2), 7.0) + self.assertEqual(number.get_atom_density(1, 2), 8.0) + self.assertEqual(number.get_atom_density(2, 2), 9.0) + + + number.set_atom_density(0, 0, 5.0) + + self.assertEqual(number.get_atom_density(0, 0), 5.0) + + # Verify volume is used correctly + self.assertEqual(number[0, 0], 5.0 * 0.38) + self.assertEqual(number[1, 0], 2.0 * 0.21) + self.assertEqual(number[2, 0], 3.0 * 1.0) + self.assertEqual(number[0, 1], 4.0 * 0.38) + self.assertEqual(number[1, 1], 5.0 * 0.21) + self.assertEqual(number[2, 1], 6.0 * 1.0) + self.assertEqual(number[0, 2], 7.0 * 0.38) + self.assertEqual(number[1, 2], 8.0 * 0.21) + self.assertEqual(number[2, 2], 9.0 * 1.0) + + def test_get_mat_slice(self): + """Tests getting slices.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) + + sl = number.get_mat_slice(0) + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + sl = number.get_mat_slice("10000") + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + def test_set_mat_slice(self): + """Tests getting slices.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.set_mat_slice(0, [1.0, 2.0]) + + self.assertEqual(number[0, 0], 1.0) + self.assertEqual(number[0, 1], 2.0) + + number.set_mat_slice("10000", [3.0, 4.0]) + + self.assertEqual(number[0, 0], 3.0) + self.assertEqual(number[0, 1], 4.0) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_cecm_regression.py b/tests/deplete_tests/test_cecm_regression.py new file mode 100644 index 0000000000..23a6342000 --- /dev/null +++ b/tests/deplete_tests/test_cecm_regression.py @@ -0,0 +1,69 @@ +""" Regression tests for cecm.py""" + +import os +import unittest + +import numpy as np + +import opendeplete +from opendeplete import results +from opendeplete import utilities +import test.dummy_geometry as dummy_geometry + + +class TestCECMRegression(unittest.TestCase): + """ Regression tests for opendeplete.integrator.cecm algorithm. + + These tests integrate a simple test problem described in dummy_geometry.py. + """ + + @classmethod + def setUpClass(cls): + """ Save current directory in case integrator crashes.""" + cls.cwd = os.getcwd() + cls.results = "test_integrator_regression" + + def test_cecm(self): + """ Integral regression test of integrator algorithm using CE/CM. """ + + settings = opendeplete.Settings() + settings.dt_vec = [0.75, 0.75] + settings.output_dir = self.results + + op = dummy_geometry.DummyGeometry(settings) + + # Perform simulation using the MCNPX/MCNP6 algorithm + opendeplete.cecm(op, print_out=False) + + # Load the files + res = results.read_results(settings.output_dir + "/results.h5") + + _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") + _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") + + # Mathematica solution + s1 = [1.86872629872102, 1.395525772416039] + s2 = [2.18097439443550, 2.69429754646747] + + tol = 1.0e-13 + + self.assertLess(np.absolute(y1[1] - s1[0]), tol) + self.assertLess(np.absolute(y2[1] - s1[1]), tol) + + self.assertLess(np.absolute(y1[2] - s2[0]), tol) + self.assertLess(np.absolute(y2[2] - s2[1]), tol) + + @classmethod + def tearDownClass(cls): + """ Clean up files""" + + os.chdir(cls.cwd) + + opendeplete.comm.barrier() + if opendeplete.comm.rank == 0: + os.remove(os.path.join(cls.results, "results.h5")) + os.rmdir(cls.results) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_cram.py b/tests/deplete_tests/test_cram.py new file mode 100644 index 0000000000..2744adbf48 --- /dev/null +++ b/tests/deplete_tests/test_cram.py @@ -0,0 +1,48 @@ +""" Tests for cram.py """ + +import unittest + +import numpy as np +import scipy.sparse as sp + +from opendeplete.integrator import CRAM16, CRAM48 + +class TestCram(unittest.TestCase): + """ Tests for cram.py + + Compares a few Mathematica matrix exponentials to CRAM16/CRAM48. + """ + + def test_CRAM16(self): + """ Test 16-term CRAM. """ + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 + + z = CRAM16(mat, x, dt) + + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) + + tol = 1.0e-15 + + self.assertLess(np.linalg.norm(z - z0), tol) + + def test_CRAM48(self): + """ Test 48-term CRAM. """ + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 + + z = CRAM48(mat, x, dt) + + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) + + tol = 1.0e-15 + + self.assertLess(np.linalg.norm(z - z0), tol) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_depletion_chain.py b/tests/deplete_tests/test_depletion_chain.py new file mode 100644 index 0000000000..216d1e68f7 --- /dev/null +++ b/tests/deplete_tests/test_depletion_chain.py @@ -0,0 +1,197 @@ +""" Tests for depletion_chain.py""" + +from collections import OrderedDict +import os +import unittest + +import numpy as np + +from opendeplete import comm, depletion_chain, reaction_rates, nuclide + + +class TestDepletionChain(unittest.TestCase): + """ Tests for DepletionChain class.""" + + def test__init__(self): + """ Test depletion chain initialization.""" + dep = depletion_chain.DepletionChain() + + self.assertIsInstance(dep.nuclides, list) + self.assertIsInstance(dep.nuclide_dict, OrderedDict) + self.assertIsInstance(dep.react_to_ind, OrderedDict) + + def test_n_nuclides(self): + """ Test depletion chain n_nuclides parameter. """ + dep = depletion_chain.DepletionChain() + + dep.nuclides = ["NucA", "NucB", "NucC"] + + self.assertEqual(dep.n_nuclides, 3) + + def test_from_endf(self): + """Test depletion chain building from ENDF. Empty at the moment until we figure + out a good way to unit-test this.""" + pass + + def test_xml_read(self): + """ Read chain_test.xml and ensure all values are correct. """ + # Unfortunately, this routine touches a lot of the code, but most of + # the components external to depletion_chain.py are simple storage + # types. + + dep = depletion_chain.DepletionChain.xml_read("chains/chain_test.xml") + + # Basic checks + self.assertEqual(dep.n_nuclides, 3) + + # A tests + nuc = dep.nuclides[dep.nuclide_dict["A"]] + + self.assertEqual(nuc.name, "A") + self.assertEqual(nuc.half_life, 2.36520E+04) + self.assertEqual(nuc.n_decay_modes, 2) + modes = nuc.decay_modes + self.assertEqual([m.target for m in modes], ["B", "C"]) + self.assertEqual([m.type for m in modes], ["beta1", "beta2"]) + self.assertEqual([m.branching_ratio for m in modes], [0.6, 0.4]) + self.assertEqual(nuc.n_reaction_paths, 1) + self.assertEqual([r.target for r in nuc.reactions], ["C"]) + self.assertEqual([r.type for r in nuc.reactions], ["(n,gamma)"]) + self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0]) + + # B tests + nuc = dep.nuclides[dep.nuclide_dict["B"]] + + self.assertEqual(nuc.name, "B") + self.assertEqual(nuc.half_life, 3.29040E+04) + self.assertEqual(nuc.n_decay_modes, 1) + modes = nuc.decay_modes + self.assertEqual([m.target for m in modes], ["A"]) + self.assertEqual([m.type for m in modes], ["beta"]) + self.assertEqual([m.branching_ratio for m in modes], [1.0]) + self.assertEqual(nuc.n_reaction_paths, 1) + self.assertEqual([r.target for r in nuc.reactions], ["C"]) + self.assertEqual([r.type for r in nuc.reactions], ["(n,gamma)"]) + self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0]) + + # C tests + nuc = dep.nuclides[dep.nuclide_dict["C"]] + + self.assertEqual(nuc.name, "C") + self.assertEqual(nuc.n_decay_modes, 0) + self.assertEqual(nuc.n_reaction_paths, 3) + self.assertEqual([r.target for r in nuc.reactions], [None, "A", "B"]) + self.assertEqual([r.type for r in nuc.reactions], ["fission", "(n,gamma)", "(n,gamma)"]) + self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0, 0.7, 0.3]) + + # Yield tests + self.assertEqual(nuc.yield_energies, [0.0253]) + self.assertEqual(list(nuc.yield_data.keys()), [0.0253]) + self.assertEqual(nuc.yield_data[0.0253], + [("A", 0.0292737), ("B", 0.002566345)]) + + def test_xml_write(self): + """Test writing a depletion chain to XML.""" + + # Prevent different MPI ranks from conflicting + filename = 'test%u.xml' % comm.rank + + A = nuclide.Nuclide() + A.name = "A" + A.half_life = 2.36520e4 + A.decay_modes = [ + nuclide.DecayTuple("beta1", "B", 0.6), + nuclide.DecayTuple("beta2", "C", 0.4) + ] + A.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + B = nuclide.Nuclide() + B.name = "B" + B.half_life = 3.29040e4 + B.decay_modes = [nuclide.DecayTuple("beta", "A", 1.0)] + B.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + C = nuclide.Nuclide() + C.name = "C" + C.reactions = [ + nuclide.ReactionTuple("fission", None, 2.0e8, 1.0), + nuclide.ReactionTuple("(n,gamma)", "A", 0.0, 0.7), + nuclide.ReactionTuple("(n,gamma)", "B", 0.0, 0.3) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + + chain = depletion_chain.DepletionChain() + chain.nuclides = [A, B, C] + chain.xml_write(filename) + + original = open('chains/chain_test.xml', 'r').read() + chain_xml = open(filename, 'r').read() + self.assertEqual(original, chain_xml) + + os.remove(filename) + + def test_form_matrix(self): + """ Using chain_test, and a dummy reaction rate, compute the matrix. """ + # Relies on test_xml_read passing. + + dep = depletion_chain.DepletionChain.xml_read("chains/chain_test.xml") + + cell_ind = {"10000": 0, "10001": 1} + nuc_ind = {"A": 0, "B": 1, "C": 2} + react_ind = dep.react_to_ind + + react = reaction_rates.ReactionRates(cell_ind, nuc_ind, react_ind) + + dep.nuc_to_react_ind = nuc_ind + + react["10000", "C", "fission"] = 1.0 + react["10000", "A", "(n,gamma)"] = 2.0 + react["10000", "B", "(n,gamma)"] = 3.0 + react["10000", "C", "(n,gamma)"] = 4.0 + + mat = dep.form_matrix(react[0, :, :]) + # Loss A, decay, (n, gamma) + mat00 = -np.log(2) / 2.36520E+04 - 2 + # A -> B, decay, 0.6 branching ratio + mat10 = np.log(2) / 2.36520E+04 * 0.6 + # A -> C, decay, 0.4 branching ratio + (n,gamma) + mat20 = np.log(2) / 2.36520E+04 * 0.4 + 2 + + # B -> A, decay, 1.0 branching ratio + mat01 = np.log(2)/3.29040E+04 + # Loss B, decay, (n, gamma) + mat11 = -np.log(2)/3.29040E+04 - 3 + # B -> C, (n, gamma) + mat21 = 3 + + # C -> A fission, (n, gamma) + mat02 = 0.0292737 * 1.0 + 4.0 * 0.7 + # C -> B fission, (n, gamma) + mat12 = 0.002566345 * 1.0 + 4.0 * 0.3 + # Loss C, fission, (n, gamma) + mat22 = -1.0 - 4.0 + + self.assertEqual(mat[0, 0], mat00) + self.assertEqual(mat[1, 0], mat10) + self.assertEqual(mat[2, 0], mat20) + self.assertEqual(mat[0, 1], mat01) + self.assertEqual(mat[1, 1], mat11) + self.assertEqual(mat[2, 1], mat21) + self.assertEqual(mat[0, 2], mat02) + self.assertEqual(mat[1, 2], mat12) + self.assertEqual(mat[2, 2], mat22) + + def test_nuc_by_ind(self): + """ Test nuc_by_ind converter function. """ + dep = depletion_chain.DepletionChain() + + dep.nuclides = ["NucA", "NucB", "NucC"] + dep.nuclide_dict = {"NucA" : 0, "NucB" : 1, "NucC" : 2} + + self.assertEqual("NucA", dep.nuc_by_ind("NucA")) + self.assertEqual("NucB", dep.nuc_by_ind("NucB")) + self.assertEqual("NucC", dep.nuc_by_ind("NucC")) + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_full.py b/tests/deplete_tests/test_full.py new file mode 100644 index 0000000000..f9a6c7493d --- /dev/null +++ b/tests/deplete_tests/test_full.py @@ -0,0 +1,119 @@ +""" Full system test suite. """ + +import shutil +import unittest + +import numpy as np + +import opendeplete +from opendeplete import results +from opendeplete import utilities +import test.example_geometry as example_geometry + + +class TestFull(unittest.TestCase): + """ Full system test suite. + + Runs an entire OpenMC simulation with depletion coupling and verifies + that the outputs match a reference file. Sensitive to changes in + OpenMC. + """ + + def test_full(self): + """ + This test runs a complete OpenMC simulation and tests the outputs. + It will take a while. + """ + + n_rings = 2 + n_wedges = 4 + + # Load geometry from example + geometry, lower_left, upper_right = \ + example_geometry.generate_problem(n_rings=n_rings, n_wedges=n_wedges) + + # Create dt vector for 3 steps with 15 day timesteps + dt1 = 15*24*60*60 # 15 days + dt2 = 1.5*30*24*60*60 # 1.5 months + N = np.floor(dt2/dt1) + + dt = np.repeat([dt1], N) + + # Create settings variable + settings = opendeplete.OpenMCSettings() + + settings.chain_file = "chains/chain_simple.xml" + settings.openmc_call = "openmc" + settings.openmc_npernode = 2 + settings.particles = 100 + settings.batches = 100 + settings.inactive = 40 + settings.lower_left = lower_left + settings.upper_right = upper_right + settings.entropy_dimension = [10, 10, 1] + + settings.round_number = True + settings.constant_seed = 1 + + joule_per_mev = 1.6021766208e-13 + settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO + settings.dt_vec = dt + settings.output_dir = "test_full" + + op = opendeplete.OpenMCOperator(geometry, settings) + + # Perform simulation using the predictor algorithm + opendeplete.integrator.predictor(op) + + # Load the files + res_test = results.read_results(settings.output_dir + "/results.h5") + + # Load the reference + res_old = results.read_results("test/test_reference.h5") + + # Assert same mats + for mat in res_old[0].mat_to_ind: + self.assertIn(mat, res_test[0].mat_to_ind, + msg="Cell " + mat + " not in new results.") + for nuc in res_old[0].nuc_to_ind: + self.assertIn(nuc, res_test[0].nuc_to_ind, + msg="Nuclide " + nuc + " not in new results.") + + for mat in res_test[0].mat_to_ind: + self.assertIn(mat, res_old[0].mat_to_ind, + msg="Cell " + mat + " not in old results.") + for nuc in res_test[0].nuc_to_ind: + self.assertIn(nuc, res_old[0].nuc_to_ind, + msg="Nuclide " + nuc + " not in old results.") + + for mat in res_test[0].mat_to_ind: + for nuc in res_test[0].nuc_to_ind: + _, y_test = utilities.evaluate_single_nuclide(res_test, mat, nuc) + _, y_old = utilities.evaluate_single_nuclide(res_old, mat, nuc) + + # Test each point + + tol = 1.0e-6 + + correct = True + for i, ref in enumerate(y_old): + if ref != y_test[i]: + if ref != 0.0: + if np.abs(y_test[i] - ref) / ref > tol: + correct = False + else: + correct = False + + self.assertTrue(correct, + msg="Discrepancy in mat " + mat + " and nuc " + nuc + + "\n" + str(y_old) + "\n" + str(y_test)) + + def tearDown(self): + """ Clean up files""" + opendeplete.comm.barrier() + if opendeplete.comm.rank == 0: + shutil.rmtree("test_full", ignore_errors=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_integrator.py b/tests/deplete_tests/test_integrator.py new file mode 100644 index 0000000000..7e121ce167 --- /dev/null +++ b/tests/deplete_tests/test_integrator.py @@ -0,0 +1,116 @@ +""" Tests for integrator.py """ + +import copy +import os +import unittest +from unittest.mock import MagicMock + +import numpy as np + +from opendeplete import integrator, ReactionRates, results, comm + + +class TestIntegrator(unittest.TestCase): + """ Tests for integrator.py + + It is worth noting that opendeplete.integrate is extremely complex, to + the point I am unsure if it can be reasonably unit-tested. For the time + being, it will be left unimplemented and testing will be done via + regression (in test_integrator_regression.py) + """ + + def test_save_results(self): + """ Test data save module """ + + stages = 3 + + np.random.seed(comm.rank) + + # Mock geometry + op = MagicMock() + + vol_dict = {} + full_burn_dict = {} + + j = 0 + for i in range(comm.size): + vol_dict[str(2*i)] = 1.2 + vol_dict[str(2*i + 1)] = 1.2 + full_burn_dict[str(2*i)] = j + full_burn_dict[str(2*i + 1)] = j + 1 + j += 2 + + burn_list = [str(i) for i in range(2*comm.rank, 2*comm.rank + 2)] + nuc_list = ["na", "nb"] + + op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_dict + + # Construct x + x1 = [] + x2 = [] + + for i in range(stages): + x1.append([np.random.rand(2), np.random.rand(2)]) + x2.append([np.random.rand(2), np.random.rand(2)]) + + # Construct r + cell_dict = {s:i for i, s in enumerate(burn_list)} + r1 = ReactionRates(cell_dict, {"na":0, "nb":1}, {"ra":0, "rb":1}) + r1.rates = np.random.rand(2, 2, 2) + + rate1 = [] + rate2 = [] + + for i in range(stages): + rate1.append(copy.deepcopy(r1)) + r1.rates = np.random.rand(2, 2, 2) + rate2.append(copy.deepcopy(r1)) + r1.rates = np.random.rand(2, 2, 2) + + # Create global terms + eigvl1 = np.random.rand(stages) + eigvl2 = np.random.rand(stages) + seed1 = [np.random.randint(100) for i in range(stages)] + seed2 = [np.random.randint(100) for i in range(stages)] + + eigvl1 = comm.bcast(eigvl1, root=0) + eigvl2 = comm.bcast(eigvl2, root=0) + seed1 = comm.bcast(seed1, root=0) + seed2 = comm.bcast(seed2, root=0) + + t1 = [0.0, 1.0] + t2 = [1.0, 2.0] + + integrator.save_results(op, x1, rate1, eigvl1, seed1, t1, 0) + integrator.save_results(op, x2, rate2, eigvl2, seed2, t2, 1) + + # Load the files + res = results.read_results("results.h5") + + for i in range(stages): + for mat_i, mat in enumerate(burn_list): + + for nuc_i, nuc in enumerate(nuc_list): + self.assertEqual(res[0][i, mat, nuc], x1[i][mat_i][nuc_i]) + self.assertEqual(res[1][i, mat, nuc], x2[i][mat_i][nuc_i]) + np.testing.assert_array_equal(res[0].rates[i][mat, nuc, :], + rate1[i][mat, nuc, :]) + np.testing.assert_array_equal(res[1].rates[i][mat, nuc, :], + rate2[i][mat, nuc, :]) + + np.testing.assert_array_equal(res[0].k, eigvl1) + np.testing.assert_array_equal(res[0].seeds, seed1) + np.testing.assert_array_equal(res[0].time, t1) + + np.testing.assert_array_equal(res[1].k, eigvl2) + np.testing.assert_array_equal(res[1].seeds, seed2) + np.testing.assert_array_equal(res[1].time, t2) + + # Delete files + comm.barrier() + if comm.rank == 0: + os.remove("results.h5") + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_nuclide.py b/tests/deplete_tests/test_nuclide.py new file mode 100644 index 0000000000..c5439b2aa3 --- /dev/null +++ b/tests/deplete_tests/test_nuclide.py @@ -0,0 +1,121 @@ +""" Tests for nuclide.py. """ + +import unittest +import xml.etree.ElementTree as ET + +from opendeplete import nuclide + + +class TestNuclide(unittest.TestCase): + """ Tests for the nuclide class. """ + + def test_n_decay_modes(self): + """ Test the decay mode count parameter. """ + + nuc = nuclide.Nuclide() + + nuc.decay_modes = [ + nuclide.DecayTuple("beta1", "a", 0.5), + nuclide.DecayTuple("beta2", "b", 0.3), + nuclide.DecayTuple("beta3", "c", 0.2) + ] + + self.assertEqual(nuc.n_decay_modes, 3) + + def test_n_reaction_paths(self): + """ Test the reaction path count parameter. """ + + nuc = nuclide.Nuclide() + + nuc.reactions = [ + nuclide.ReactionTuple("(n,2n)", "a", 0.0, 1.0), + nuclide.ReactionTuple("(n,3n)", "b", 0.0, 1.0), + nuclide.ReactionTuple("(n,4n)", "c", 0.0, 1.0) + ] + + self.assertEqual(nuc.n_reaction_paths, 3) + + def test_xml_read(self): + """Test reading nuclide data from an XML element.""" + + data = """ + + + + + + + + + + 0.0253 + + Te134 Zr100 Xe138 + 0.062155 0.0497641 0.0481413 + + + + """ + + element = ET.fromstring(data) + u235 = nuclide.Nuclide.xml_read(element) + + self.assertEqual(u235.decay_modes, [ + nuclide.DecayTuple('sf', 'U235', 7.2e-11), + nuclide.DecayTuple('alpha', 'Th231', 1 - 7.2e-11) + ]) + self.assertEqual(u235.reactions, [ + nuclide.ReactionTuple('(n,2n)', 'U234', -5297781.0, 1.0), + nuclide.ReactionTuple('(n,3n)', 'U233', -12142300.0, 1.0), + nuclide.ReactionTuple('(n,4n)', 'U232', -17885600.0, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'U236', 6545200.0, 1.0), + nuclide.ReactionTuple('fission', None, 193405400.0, 1.0), + ]) + self.assertEqual(u235.yield_energies, [0.0253]) + self.assertEqual(u235.yield_data, { + 0.0253: [('Te134', 0.062155), ('Zr100', 0.0497641), + ('Xe138', 0.0481413)] + }) + + def test_xml_write(self): + """Test writing nuclide data to an XML element.""" + + C = nuclide.Nuclide() + C.name = "C" + C.half_life = 0.123 + C.decay_modes = [ + nuclide.DecayTuple('beta-', 'B', 0.99), + nuclide.DecayTuple('alpha', 'D', 0.01) + ] + C.reactions = [ + nuclide.ReactionTuple('fission', None, 2.0e8, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'A', 0.0, 1.0) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + element = C.xml_write() + + self.assertEqual(element.get("half_life"), "0.123") + + decay_elems = element.findall("decay_type") + self.assertEqual(len(decay_elems), 2) + self.assertEqual(decay_elems[0].get("type"), "beta-") + self.assertEqual(decay_elems[0].get("target"), "B") + self.assertEqual(decay_elems[0].get("branching_ratio"), "0.99") + self.assertEqual(decay_elems[1].get("type"), "alpha") + self.assertEqual(decay_elems[1].get("target"), "D") + self.assertEqual(decay_elems[1].get("branching_ratio"), "0.01") + + rx_elems = element.findall("reaction_type") + self.assertEqual(len(rx_elems), 2) + self.assertEqual(rx_elems[0].get("type"), "fission") + self.assertEqual(float(rx_elems[0].get("Q")), 2.0e8) + self.assertEqual(rx_elems[1].get("type"), "(n,gamma)") + self.assertEqual(rx_elems[1].get("target"), "A") + self.assertEqual(float(rx_elems[1].get("Q")), 0.0) + + self.assertIsNotNone(element.find('neutron_fission_yields')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_predictor_regression.py b/tests/deplete_tests/test_predictor_regression.py new file mode 100644 index 0000000000..c72ae8a475 --- /dev/null +++ b/tests/deplete_tests/test_predictor_regression.py @@ -0,0 +1,68 @@ +""" Regression tests for predictor.py""" + +import os +import unittest + +import numpy as np + +import opendeplete +from opendeplete import results +from opendeplete import utilities +import test.dummy_geometry as dummy_geometry + +class TestPredictorRegression(unittest.TestCase): + """ Regression tests for opendeplete.integrator.predictor algorithm. + + These tests integrate a simple test problem described in dummy_geometry.py. + """ + + @classmethod + def setUpClass(cls): + """ Save current directory in case integrator crashes.""" + cls.cwd = os.getcwd() + cls.results = "test_integrator_regression" + + def test_predictor(self): + """ Integral regression test of integrator algorithm using CE/CM. """ + + settings = opendeplete.Settings() + settings.dt_vec = [0.75, 0.75] + settings.output_dir = self.results + + op = dummy_geometry.DummyGeometry(settings) + + # Perform simulation using the predictor algorithm + opendeplete.predictor(op, print_out=False) + + # Load the files + res = results.read_results(settings.output_dir + "/results.h5") + + _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") + _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") + + # Mathematica solution + s1 = [2.46847546272295, 0.986431226850467] + s2 = [4.11525874568034, -0.0581692232513460] + + tol = 1.0e-13 + + self.assertLess(np.absolute(y1[1] - s1[0]), tol) + self.assertLess(np.absolute(y2[1] - s1[1]), tol) + + self.assertLess(np.absolute(y1[2] - s2[0]), tol) + self.assertLess(np.absolute(y2[2] - s2[1]), tol) + + @classmethod + def tearDownClass(cls): + """ Clean up files""" + + os.chdir(cls.cwd) + + opendeplete.comm.barrier() + if opendeplete.comm.rank == 0: + os.remove(os.path.join(cls.results, "results.h5")) + os.rmdir(cls.results) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_reaction_rates.py b/tests/deplete_tests/test_reaction_rates.py new file mode 100644 index 0000000000..4821ec18cd --- /dev/null +++ b/tests/deplete_tests/test_reaction_rates.py @@ -0,0 +1,86 @@ +""" Tests for reaction_rates.py. """ + +import unittest + +from opendeplete import reaction_rates + + +class TestReactionRates(unittest.TestCase): + """ Tests for the ReactionRates class. """ + + def test_indexing(self): + """Tests the __getitem__ and __setitem__ routines simultaneously.""" + + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + rates["10000", "U238", "fission"] = 1.0 + rates["10001", "U238", "fission"] = 2.0 + rates["10000", "U235", "fission"] = 3.0 + rates["10001", "U235", "fission"] = 4.0 + rates["10000", "U238", "(n,gamma)"] = 5.0 + rates["10001", "U238", "(n,gamma)"] = 6.0 + rates["10000", "U235", "(n,gamma)"] = 7.0 + rates["10001", "U235", "(n,gamma)"] = 8.0 + + # String indexing + self.assertEqual(rates["10000", "U238", "fission"], 1.0) + self.assertEqual(rates["10001", "U238", "fission"], 2.0) + self.assertEqual(rates["10000", "U235", "fission"], 3.0) + self.assertEqual(rates["10001", "U235", "fission"], 4.0) + self.assertEqual(rates["10000", "U238", "(n,gamma)"], 5.0) + self.assertEqual(rates["10001", "U238", "(n,gamma)"], 6.0) + self.assertEqual(rates["10000", "U235", "(n,gamma)"], 7.0) + self.assertEqual(rates["10001", "U235", "(n,gamma)"], 8.0) + + # Int indexing + self.assertEqual(rates[0, 0, 0], 1.0) + self.assertEqual(rates[1, 0, 0], 2.0) + self.assertEqual(rates[0, 1, 0], 3.0) + self.assertEqual(rates[1, 1, 0], 4.0) + self.assertEqual(rates[0, 0, 1], 5.0) + self.assertEqual(rates[1, 0, 1], 6.0) + self.assertEqual(rates[0, 1, 1], 7.0) + self.assertEqual(rates[1, 1, 1], 8.0) + + rates[0, 0, 0] = 5.0 + + self.assertEqual(rates[0, 0, 0], 5.0) + self.assertEqual(rates["10000", "U238", "fission"], 5.0) + + def test_n_mat(self): + """ Test number of materials property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + self.assertEqual(rates.n_mat, 2) + + def test_n_nuc(self): + """ Test number of nuclides property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + self.assertEqual(rates.n_nuc, 3) + + def test_n_react(self): + """ Test number of reactions property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + self.assertEqual(rates.n_react, 4) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/deplete_tests/test_reference.h5 b/tests/deplete_tests/test_reference.h5 new file mode 100644 index 0000000000000000000000000000000000000000..ef3ae0090943bc7ecdc01a1afaa70c0216e029f0 GIT binary patch literal 165384 zcmeEP2|QHY`yXo(5<+PakxKS8?ltZmOC%~qJC&lclonD_+O=p=+9Z{fii*%WC}|TF zX%{0zWi2i8ztcT;&TD?}^uBuY)9?S@>60_hxzByhbH3;KKIhz-bMI`hXW2?i_LgLD zUlI}wQHJdIx743j@RC?7{Jn~jspB5tjSwi;gEE0sX9#`&$6zRf`X0bOzn<$D8yf~g zm_ga6N^lxOPn3LT1}aqZ$QC6i1-kryjexz4wF|d{$)J}3po~tWA`evj;zEcaPDC*A z0?i09$cUp_6(Qo8`(Bo)CXX<=+6*y5;?@fb34d3WAQ-@XBSIMf+FV`kOYRSLM;eDt zU@#)d1Hakdv7?+>LVw5-L1LtX-#baXjRi85M!pXkQEz{e()jZZQTZXiAE`%aHv?ID z09nK1|0qi1&+Yy0wSw{@KYnChlogm4W#!49dVmfmW8|AKAg7Ne-^c|EF4&)#} zq+%e4tsvjj0(t!w@{KHjJMsW2t5V1H$T#lbco>_MwZQS9Gvu3OaJ=|2DHj9TrG}Ji zft>q|lx4yEkuOaipvJwp4=LM|YXADbLPVzFBBBhCkOjnZS0F2r{{kTZGh^{K$6{2z z!3qpRo3p}l46WN#&;pGBjR1`RjR1`Rjllmj0@QUC8!QCuK^c9L?3SSQg|abuoLXN9 z((?cdH%gBJi(J<-1g>i-J-YmNB0$BZJLo=nZOve$%eBRWT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LmbwtpYrYBAC80d&u0H!3s(jBJy?B0VU~DI7QMEMI|vyD{Xf4y>swqDLVuip zuW!m{({&+m?0XmqtgC9zEDIxFF|3BYMo@*x8ujGIK2Vcfo&;S4c literal 0 HcmV?d00001 diff --git a/tests/deplete_tests/test_utilities.py b/tests/deplete_tests/test_utilities.py new file mode 100644 index 0000000000..faa1a500b4 --- /dev/null +++ b/tests/deplete_tests/test_utilities.py @@ -0,0 +1,68 @@ +""" Full system test suite. """ + +import unittest + +import numpy as np + +from opendeplete import results +from opendeplete import utilities + + +class TestUtilities(unittest.TestCase): + """ Tests the utilities classes. + + This also tests the results read/write code. + """ + + def test_evaluate_single_nuclide(self): + """ Tests evaluating single nuclide utility code. + """ + + # Load the reference + res = results.read_results("test/test_reference.h5") + + x, y = utilities.evaluate_single_nuclide(res, "1", "Xe135") + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + y_ref = [6.6747328233649218e+08, 3.5519299354458244e+14, + 3.4599104054580338e+14, 3.3821165110278112e+14] + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, y_ref) + + def test_evaluate_reaction_rate(self): + """ Tests evaluating reaction rate utility code. + """ + + # Load the reference + res = results.read_results("test/test_reference.h5") + + x, y = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + xe_ref = np.array([6.6747328233649218e+08, 3.5519299354458244e+14, + 3.4599104054580338e+14, 3.3821165110278112e+14]) + r_ref = np.array([4.0643598574337784e-05, 4.1457730544386974e-05, + 3.4121248544056681e-05, 3.9204686657643301e-05]) + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, xe_ref * r_ref) + + def test_evaluate_eigenvalue(self): + """ Tests evaluating eigenvalue + """ + + # Load the reference + res = results.read_results("test/test_reference.h5") + + x, y = utilities.evaluate_eigenvalue(res) + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + y_ref = [1.1921986054449838, 1.1712785643938586, 1.1927099024502694, 1.2269183590698847] + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, y_ref) + + +if __name__ == '__main__': + unittest.main() From 37f552a5dcdcb2d16d9db21e95f099c214c3bda7 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 14:01:59 -0600 Subject: [PATCH 103/212] Fix deplete imports --- openmc/deplete/__init__.py | 6 +-- openmc/deplete/atom_number.py | 18 +++---- openmc/deplete/depletion_chain.py | 18 +++---- openmc/deplete/function.py | 14 ++--- openmc/deplete/integrator/save_results.py | 3 +- openmc/deplete/openmc_wrapper.py | 52 +++++++++---------- openmc/deplete/reaction_rates.py | 6 +-- openmc/deplete/results.py | 23 ++++---- openmc/deplete/utilities.py | 10 ++-- scripts/example_geometry.py | 3 +- scripts/example_plot.py | 7 +-- scripts/example_run.py | 8 +-- scripts/make_chain.py | 4 +- tests/deplete_tests/dummy_geometry.py | 22 +++----- tests/deplete_tests/test_atom_number.py | 12 ++--- tests/deplete_tests/test_cecm_regression.py | 16 +++--- tests/deplete_tests/test_cram.py | 2 +- tests/deplete_tests/test_depletion_chain.py | 3 +- tests/deplete_tests/test_full.py | 22 ++++---- tests/deplete_tests/test_integrator.py | 3 +- tests/deplete_tests/test_nuclide.py | 2 +- .../test_predictor_regression.py | 16 +++--- tests/deplete_tests/test_reaction_rates.py | 2 +- tests/deplete_tests/test_utilities.py | 15 +++--- 24 files changed, 141 insertions(+), 146 deletions(-) diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py index 994a51e12c..4bdde3935e 100644 --- a/openmc/deplete/__init__.py +++ b/openmc/deplete/__init__.py @@ -1,8 +1,8 @@ """ -OpenDeplete -=========== +openmc.deplete +============== -A simple depletion front-end tool. +A depletion front-end tool. """ from .dummy_comm import DummyCommunicator diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 03bedbf531..63c9af8364 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -7,7 +7,7 @@ import numpy as np class AtomNumber(object): - """ AtomNumber module. + """AtomNumber module. An ndarray to store atom densities with string, integer, or slice indexing. @@ -71,7 +71,7 @@ class AtomNumber(object): self._burn_mat_list = None def __getitem__(self, pos): - """ Retrieves total atom number from AtomNumber. + """Retrieves total atom number from AtomNumber. Parameters ---------- @@ -95,7 +95,7 @@ class AtomNumber(object): return self.number[mat, nuc] def __setitem__(self, pos, val): - """ Sets total atom number into AtomNumber. + """Sets total atom number into AtomNumber. Parameters ---------- @@ -116,7 +116,7 @@ class AtomNumber(object): self.number[mat, nuc] = val def get_atom_density(self, mat, nuc): - """ Accesses atom density instead of total number. + """Accesses atom density instead of total number. Parameters ---------- @@ -139,7 +139,7 @@ class AtomNumber(object): return self[mat, nuc] / self.volume[mat] def set_atom_density(self, mat, nuc, val): - """ Sets atom density instead of total number. + """Sets atom density instead of total number. Parameters ---------- @@ -159,7 +159,7 @@ class AtomNumber(object): self[mat, nuc] = val * self.volume[mat] def get_mat_slice(self, mat): - """ Gets atom quantity indexed by mats for all burned nuclides + """Gets atom quantity indexed by mats for all burned nuclides Parameters ---------- @@ -178,7 +178,7 @@ class AtomNumber(object): return self[mat, 0:self.n_nuc_burn] def set_mat_slice(self, mat, val): - """ Sets atom quantity indexed by mats for all burned nuclides + """Sets atom quantity indexed by mats for all burned nuclides Parameters ---------- @@ -205,7 +205,7 @@ class AtomNumber(object): @property def burn_nuc_list(self): - """ burn_nuc_list : list of str + """burn_nuc_list : list of str A list of all nuclide material names. Used for sorting the simulation. """ @@ -221,7 +221,7 @@ class AtomNumber(object): @property def burn_mat_list(self): - """ burn_mat_list : list of str + """burn_mat_list : list of str A list of all burning material names. Used for sorting the simulation. """ diff --git a/openmc/deplete/depletion_chain.py b/openmc/deplete/depletion_chain.py index 05cc9db435..af126035f6 100644 --- a/openmc/deplete/depletion_chain.py +++ b/openmc/deplete/depletion_chain.py @@ -11,9 +11,6 @@ import math import re import os -from tqdm import tqdm -import scipy.sparse as sp -import openmc.data # Try to use lxml if it is available. It preserves the order of attributes and # provides a pretty-printer by default. If not available, use OpenMC function to # pretty print. @@ -22,9 +19,12 @@ try: _have_lxml = True except ImportError: import xml.etree.ElementTree as ET - from openmc.clean_xml import clean_xml_indentation _have_lxml = False +from tqdm import tqdm +import scipy.sparse as sp +import openmc.data +from openmc.clean_xml import clean_xml_indentation from .nuclide import Nuclide, DecayTuple, ReactionTuple @@ -109,7 +109,7 @@ def replace_missing(product, decay_data): class DepletionChain(object): - """ The DepletionChain class. + """The DepletionChain class. This class contains a full representation of a depletion chain. @@ -334,7 +334,7 @@ class DepletionChain(object): # Load XML tree try: root = ET.parse(filename) - except: + except Exception: if filename is None: print("No chain specified, either manually or in environment variable OPENDEPLETE_CHAIN.") else: @@ -374,11 +374,11 @@ class DepletionChain(object): if _have_lxml: tree.write(filename, encoding='utf-8', pretty_print=True) else: - clean_xml_indentation(root_elem, spaces_per_level=2) + clean_xml_indentation(root_elem) tree.write(filename, encoding='utf-8') def form_matrix(self, rates): - """ Forms depletion matrix. + """Forms depletion matrix. Parameters ---------- @@ -457,7 +457,7 @@ class DepletionChain(object): return matrix_dok.tocsr() def nuc_by_ind(self, ind): - """ Extracts nuclides from the list by dictionary key. + """Extracts nuclides from the list by dictionary key. Parameters ---------- diff --git a/openmc/deplete/function.py b/openmc/deplete/function.py index 74eb92422b..bcc055e67b 100644 --- a/openmc/deplete/function.py +++ b/openmc/deplete/function.py @@ -6,8 +6,9 @@ to run a full depletion simulation. from abc import ABCMeta, abstractmethod + class Settings(object): - """ The Settings class. + """The Settings class. Contains all parameters necessary for the integrator. @@ -24,8 +25,9 @@ class Settings(object): self.dt_vec = None self.output_dir = None + class Operator(metaclass=ABCMeta): - """ The Operator metaclass. + """The Operator metaclass. This defines all functions that the integrator needs to operate. @@ -40,7 +42,7 @@ class Operator(metaclass=ABCMeta): @abstractmethod def initial_condition(self): - """ Performs final setup and returns initial condition. + """Performs final setup and returns initial condition. Returns ------- @@ -52,7 +54,7 @@ class Operator(metaclass=ABCMeta): @abstractmethod def eval(self, vec, print_out=True): - """ Runs a simulation. + """Runs a simulation. Parameters ---------- @@ -75,7 +77,7 @@ class Operator(metaclass=ABCMeta): @abstractmethod def get_results_info(self): - """ Returns volume list, cell lists, and nuc lists. + """Returns volume list, cell lists, and nuc lists. Returns ------- @@ -93,7 +95,7 @@ class Operator(metaclass=ABCMeta): @abstractmethod def form_matrix(self, y, mat): - """ Forms the f(y) matrix in y' = f(y)y. + """Forms the f(y) matrix in y' = f(y)y. Nominally a depletion matrix, this is abstracted on the off chance that the function f has nothing to do with depletion at all. diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index 35cbc7f3f1..4f20b52fde 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -1,7 +1,8 @@ """ Generic result saving code for integrators. """ -from opendeplete.results import Results, write_results +from ..results import Results, write_results + def save_results(op, x, rates, eigvls, seeds, t, step_ind): """ Creates and writes results to disk diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 347dc71857..05b5057d20 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -1,6 +1,6 @@ -""" The OpenMC wrapper module. +"""The OpenMC wrapper module. -This module implements the OpenDeplete -> OpenMC linkage. +This module implements the depletion -> OpenMC linkage. """ import copy @@ -14,14 +14,13 @@ try: _have_lxml = True except ImportError: import xml.etree.ElementTree as ET - from openmc.clean_xml import clean_xml_indentation _have_lxml = False import h5py import numpy as np + import openmc import openmc.capi - from . import comm from .atom_number import AtomNumber from .depletion_chain import DepletionChain @@ -194,7 +193,7 @@ class OpenMCOperator(Operator): # Clear out OpenMC, create task lists, distribute if comm.rank == 0: - clean_up_openmc() + openmc.reset_auto_ids() mat_burn_list, mat_not_burn_list, volume, self.mat_tally_ind, \ nuc_dict = self.extract_mat_ids() else: @@ -224,7 +223,7 @@ class OpenMCOperator(Operator): openmc.capi.finalize() def extract_mat_ids(self): - """ Extracts materials and assigns them to processes. + """Extracts materials and assigns them to processes. Returns ------- @@ -308,7 +307,7 @@ class OpenMCOperator(Operator): return mat_burn_lists, mat_not_burn_lists, volume, mat_tally_ind, nuc_dict def extract_number(self, mat_burn, mat_not_burn, volume, nuc_dict): - """ Construct self.number read from geometry + """Construct self.number read from geometry Parameters ---------- @@ -356,7 +355,7 @@ class OpenMCOperator(Operator): self.set_number_from_mat(mat) def set_number_from_mat(self, mat): - """ Extracts material and number densities from openmc.Material + """Extracts material and number densities from openmc.Material Parameters ---------- @@ -369,12 +368,11 @@ class OpenMCOperator(Operator): nuc_dens = mat.get_nuclide_atom_densities() for nuclide in nuc_dens: - name = nuclide.name number = nuc_dens[nuclide][1] * 1.0e24 - self.number.set_atom_density(mat_id, name, number) + self.number.set_atom_density(mat_id, nuclide, number) def initialize_reaction_rates(self): - """ Create reaction rates object. """ + """Create reaction rates object. """ self.reaction_rates = ReactionRates( self.burn_mat_to_ind, self.burn_nuc_to_ind, @@ -383,7 +381,7 @@ class OpenMCOperator(Operator): self.chain.nuc_to_react_ind = self.burn_nuc_to_ind def eval(self, vec, print_out=True): - """ Runs a simulation. + """Runs a simulation. Parameters ---------- @@ -405,7 +403,7 @@ class OpenMCOperator(Operator): """ # Prevent OpenMC from complaining about re-creating tallies - clean_up_openmc() + openmc.reset_auto_ids() # Update status self.set_density(vec) @@ -435,7 +433,7 @@ class OpenMCOperator(Operator): return k, copy.deepcopy(self.reaction_rates), self.seed def form_matrix(self, y, mat): - """ Forms the depletion matrix. + """Forms the depletion matrix. Parameters ---------- @@ -453,7 +451,7 @@ class OpenMCOperator(Operator): return copy.deepcopy(self.chain.form_matrix(y[mat, :, :])) def initial_condition(self): - """ Performs final setup and returns initial condition. + """Performs final setup and returns initial condition. Returns ------- @@ -513,7 +511,7 @@ class OpenMCOperator(Operator): mat_internal.set_densities(nuclides, densities) def generate_materials_xml(self): - """ Creates materials.xml from self.number. + """Creates materials.xml from self.number. Due to uncertainty with how MPI interacts with OpenMC API, this constructs the XML manually. The long term goal is to do this @@ -531,7 +529,7 @@ class OpenMCOperator(Operator): materials.export_to_xml() def generate_settings_xml(self): - """ Generates settings.xml. + """Generates settings.xml. This function creates settings.xml using the value of the settings variable. @@ -625,7 +623,7 @@ class OpenMCOperator(Operator): tally_dep.filters = [mat_filter] def total_density_list(self): - """ Returns a list of total density lists. + """Returns a list of total density lists. This list is in the exact same order as depletion_matrix_list, so that matrix exponentiation can be done easily. @@ -641,7 +639,7 @@ class OpenMCOperator(Operator): return total_density def set_density(self, total_density): - """ Sets density. + """Sets density. Sets the density in the exact same order as total_density_list outputs, allowing for internal consistency @@ -657,7 +655,7 @@ class OpenMCOperator(Operator): self.number.set_mat_slice(i, total_density[i]) def unpack_tallies_and_normalize(self): - """ Unpack tallies from OpenMC + """Unpack tallies from OpenMC This function reads the tallies generated by OpenMC (from the tally.xml file generated in generate_tally_xml) normalizes them so that the total @@ -754,7 +752,7 @@ class OpenMCOperator(Operator): return k_combined def load_participating(self): - """ Loads a cross_sections.xml file to find participating nuclides. + """Loads a cross_sections.xml file to find participating nuclides. This allows for nuclides that are important in the decay chain but not important neutronically, or have no cross section data. @@ -772,7 +770,7 @@ class OpenMCOperator(Operator): try: tree = ET.parse(filename) - except: + except Exception: if filename is None: msg = "No cross_sections.xml specified in materials." else: @@ -802,7 +800,7 @@ class OpenMCOperator(Operator): return len(self.chain.nuclides) def get_results_info(self): - """ Returns volume list, cell lists, and nuc lists. + """Returns volume list, cell lists, and nuc lists. Returns ------- @@ -829,8 +827,10 @@ class OpenMCOperator(Operator): return volume, nuc_list, burn_list, self.mat_tally_ind + def density_to_mat(dens_dict): - """ Generates an OpenMC material from a cell ID and self.number_density. + """Generates an OpenMC material from a cell ID and self.number_density. + Parameters ---------- m_id : int @@ -847,7 +847,3 @@ def density_to_mat(dens_dict): mat.set_density('sum') return mat - -def clean_up_openmc(): - """ Resets all automatic indexing in OpenMC, as these get in the way. """ - openmc.reset_auto_ids() diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index 7b934027a5..de3a6a7280 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -7,7 +7,7 @@ import numpy as np class ReactionRates(object): - """ ReactionRates class. + """ReactionRates class. An ndarray to store reaction rates with string, integer, or slice indexing. @@ -47,7 +47,7 @@ class ReactionRates(object): self.rates = np.zeros((self.n_mat, self.n_nuc, self.n_react)) def __getitem__(self, pos): - """ Retrieves an item from reaction_rates. + """Retrieves an item from reaction_rates. Parameters ---------- @@ -74,7 +74,7 @@ class ReactionRates(object): return self.rates[mat, nuc, react] def __setitem__(self, pos, val): - """ Sets an item from reaction_rates. + """Sets an item from reaction_rates. Parameters ---------- diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index c0ec1627ea..ae096b8ce5 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -1,4 +1,4 @@ -""" The results module. +"""The results module. Contains results generation and saving capabilities. """ @@ -14,8 +14,9 @@ from .reaction_rates import ReactionRates RESULTS_VERSION = 2 + class Results(object): - """ Contains output of opendeplete. + """Contains output of opendeplete. Attributes ---------- @@ -62,7 +63,7 @@ class Results(object): self.data = None def allocate(self, volume, nuc_list, burn_list, full_burn_dict, stages): - """ Allocates memory of Results. + """Allocates memory of Results. Parameters ---------- @@ -113,7 +114,7 @@ class Results(object): return self.data.shape[0] def __getitem__(self, pos): - """ Retrieves an item from results. + """Retrieves an item from results. Parameters ---------- @@ -137,7 +138,7 @@ class Results(object): return self.data[stage, mat, nuc] def __setitem__(self, pos, val): - """ Sets an item from results. + """Sets an item from results. Parameters ---------- @@ -159,7 +160,7 @@ class Results(object): self.data[stage, mat, nuc] = val def create_hdf5(self, handle): - """ Creates file structure for a blank HDF5 file. + """Creates file structure for a blank HDF5 file. Parameters ---------- @@ -232,7 +233,7 @@ class Results(object): handle.create_dataset("time", (1, 2), maxshape=(None, 2), dtype='float64') def to_hdf5(self, handle, index): - """ Converts results object into an hdf5 object. + """Converts results object into an hdf5 object. Parameters ---------- @@ -302,7 +303,7 @@ class Results(object): time_dset[index, :] = self.time def from_hdf5(self, handle, index): - """ Loads results object from HDF5. + """Loads results object from HDF5. Parameters ---------- @@ -360,7 +361,7 @@ class Results(object): def get_dict(number): - """ Given an operator nested dictionary, output indexing dictionaries. + """Given an operator nested dictionary, output indexing dictionaries. These indexing dictionaries map mat IDs and nuclide names to indices inside of Results.data. @@ -394,7 +395,7 @@ def get_dict(number): def write_results(result, filename, index): - """ Outputs result to an .hdf5 file. + """Outputs result to an .hdf5 file. Parameters ---------- @@ -418,7 +419,7 @@ def write_results(result, filename, index): def read_results(filename): - """ Reads out a list of results objects from an hdf5 file. + """Reads out a list of results objects from an hdf5 file. Parameters ---------- diff --git a/openmc/deplete/utilities.py b/openmc/deplete/utilities.py index 54632ed9c2..5433edce44 100644 --- a/openmc/deplete/utilities.py +++ b/openmc/deplete/utilities.py @@ -1,4 +1,4 @@ -""" The utilities module. +"""The utilities module. Contains functions that can be used to post-process objects that come out of the results module. @@ -6,8 +6,9 @@ the results module. import numpy as np + def evaluate_single_nuclide(results, cell, nuc): - """ Evaluates a single nuclide in a single cell from a results list. + """Evaluates a single nuclide in a single cell from a results list. Parameters ---------- @@ -38,7 +39,7 @@ def evaluate_single_nuclide(results, cell, nuc): return time, concentration def evaluate_reaction_rate(results, cell, nuc, rxn): - """ Evaluates a single nuclide reaction rate in a single cell from a results list. + """Evaluates a single nuclide reaction rate in a single cell from a results list. Parameters ---------- @@ -69,8 +70,9 @@ def evaluate_reaction_rate(results, cell, nuc, rxn): return time, rate + def evaluate_eigenvalue(results): - """ Evaluates the eigenvalue from a results list. + """Evaluates the eigenvalue from a results list. Parameters ---------- diff --git a/scripts/example_geometry.py b/scripts/example_geometry.py index 9afcc0d464..09ce0576f1 100644 --- a/scripts/example_geometry.py +++ b/scripts/example_geometry.py @@ -9,8 +9,7 @@ import math import numpy as np import openmc - -from opendeplete import density_to_mat +from openmc.deplete import density_to_mat def generate_initial_number_density(): diff --git a/scripts/example_plot.py b/scripts/example_plot.py index d2c6ee9d6a..c92fef6bf2 100644 --- a/scripts/example_plot.py +++ b/scripts/example_plot.py @@ -1,11 +1,8 @@ """An example file showing how to plot data from a simulation.""" import matplotlib.pyplot as plt - -from opendeplete import read_results, \ - evaluate_single_nuclide, \ - evaluate_reaction_rate, \ - evaluate_eigenvalue +from openmc.deplete import (read_results, evaluate_single_nuclide, + evaluate_reaction_rate, evaluate_eigenvalue) # Set variables for where the data is, and what we want to read out. result_folder = "test" diff --git a/scripts/example_run.py b/scripts/example_run.py index bb80f65820..82d0883c3a 100644 --- a/scripts/example_run.py +++ b/scripts/example_run.py @@ -1,7 +1,7 @@ """An example file showing how to run a simulation.""" import numpy as np -import opendeplete +import openmc.deplete import example_geometry @@ -16,7 +16,7 @@ N = np.floor(dt2/dt1) dt = np.repeat([dt1], N) # Create settings variable -settings = opendeplete.OpenMCSettings() +settings = openmc.deplete.OpenMCSettings() settings.openmc_call = "openmc" # An example for mpiexec: @@ -33,7 +33,7 @@ settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO settings.dt_vec = dt settings.output_dir = 'test' -op = opendeplete.OpenMCOperator(geometry, settings) +op = openmc.deplete.OpenMCOperator(geometry, settings) # Perform simulation using the MCNPX/MCNP6 algorithm -opendeplete.integrator.cecm(op) +openmc.deplete.integrator.cecm(op) diff --git a/scripts/make_chain.py b/scripts/make_chain.py index 2e0d9d3bc4..ccf4ef9b7b 100644 --- a/scripts/make_chain.py +++ b/scripts/make_chain.py @@ -6,7 +6,7 @@ from zipfile import ZipFile import requests from tqdm import tqdm -import opendeplete +import openmc.deplete urls = [ @@ -52,7 +52,7 @@ def main(): nfy_files = glob.glob(os.path.join('nfy', '*.endf')) neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) - chain = opendeplete.DepletionChain.from_endf(decay_files, nfy_files, neutron_files) + chain = openmc.deplete.DepletionChain.from_endf(decay_files, nfy_files, neutron_files) chain.xml_write('chain_endfb71.xml') diff --git a/tests/deplete_tests/dummy_geometry.py b/tests/deplete_tests/dummy_geometry.py index 6101519411..614cc726e3 100644 --- a/tests/deplete_tests/dummy_geometry.py +++ b/tests/deplete_tests/dummy_geometry.py @@ -1,16 +1,11 @@ -""" The OpenMC wrapper module. - -This module implements the OpenDeplete -> OpenMC linkage. -""" - import numpy as np import scipy.sparse as sp +from openmc.deplete.reaction_rates import ReactionRates +from openmc.deplete.function import Operator -from opendeplete.reaction_rates import ReactionRates -from opendeplete.function import Operator class DummyGeometry(Operator): - """ This is a dummy geometry class with no statistical uncertainty. + """This is a dummy geometry class with no statistical uncertainty. y_1' = sin(y_2) y_1 + cos(y_1) y_2 y_2' = -cos(y_2) y_1 + sin(y_1) y_2 @@ -24,14 +19,14 @@ class DummyGeometry(Operator): """ def __init__(self, settings): - Operator.__init__(self, settings) + super().__init__(settings) @property def chain(self): return self def eval(self, vec, print_out=False): - """ Evaluates F(y) + """Evaluates F(y) Parameters ---------- @@ -60,11 +55,10 @@ class DummyGeometry(Operator): reaction_rates[0, 1, 0] = vec[0][1] # Create a fake rates object - return 0.0, reaction_rates, 0 def form_matrix(self, rates): - """ Forms the f(y) matrix in y' = f(y)y. + """Forms the f(y) matrix in y' = f(y)y. Nominally a depletion matrix, this is abstracted on the off chance that the function f has nothing to do with depletion at all. @@ -137,7 +131,7 @@ class DummyGeometry(Operator): return ReactionRates(cell_to_ind, nuc_to_ind, react_to_ind) def initial_condition(self): - """ Returns initial vector. + """Returns initial vector. Returns ------- @@ -148,7 +142,7 @@ class DummyGeometry(Operator): return [np.array((1.0, 1.0))] def get_results_info(self): - """ Returns volume list, cell lists, and nuc lists. + """Returns volume list, cell lists, and nuc lists. Returns ------- diff --git a/tests/deplete_tests/test_atom_number.py b/tests/deplete_tests/test_atom_number.py index 9a17230f86..d36b96d38d 100644 --- a/tests/deplete_tests/test_atom_number.py +++ b/tests/deplete_tests/test_atom_number.py @@ -3,11 +3,11 @@ import unittest import numpy as np +from openmc.deplete import atom_number -from opendeplete import atom_number class TestAtomNumber(unittest.TestCase): - """ Tests for the AtomNumber class. """ + """Tests for the AtomNumber class.""" def test_indexing(self): """Tests the __getitem__ and __setitem__ routines simultaneously.""" @@ -41,7 +41,7 @@ class TestAtomNumber(unittest.TestCase): self.assertEqual(number["10000", "U238"], 5.0) def test_n_mat(self): - """ Test number of materials property. """ + """Test number of materials property. """ mat_to_ind = {"10000" : 0, "10001" : 1} nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} @@ -51,7 +51,7 @@ class TestAtomNumber(unittest.TestCase): self.assertEqual(number.n_mat, 2) def test_n_nuc(self): - """ Test number of nuclides property. """ + """Test number of nuclides property.""" mat_to_ind = {"10000" : 0, "10001" : 1} nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} @@ -61,7 +61,7 @@ class TestAtomNumber(unittest.TestCase): self.assertEqual(number.n_nuc, 3) def test_burn_nuc_list(self): - """ Test the list of burned nuclides property """ + """Test the list of burned nuclides property""" mat_to_ind = {"10000" : 0, "10001" : 1} nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} @@ -71,7 +71,7 @@ class TestAtomNumber(unittest.TestCase): self.assertEqual(number.burn_nuc_list, ["U238", "U235"]) def test_burn_mat_list(self): - """ Test the list of burned nuclides property """ + """Test the list of burned nuclides property""" mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} diff --git a/tests/deplete_tests/test_cecm_regression.py b/tests/deplete_tests/test_cecm_regression.py index 23a6342000..0d6966c82c 100644 --- a/tests/deplete_tests/test_cecm_regression.py +++ b/tests/deplete_tests/test_cecm_regression.py @@ -4,11 +4,11 @@ import os import unittest import numpy as np +import openmc.deplete +from openmc.deplete import results +from openmc.deplete import utilities -import opendeplete -from opendeplete import results -from opendeplete import utilities -import test.dummy_geometry as dummy_geometry +from . import dummy_geometry class TestCECMRegression(unittest.TestCase): @@ -26,14 +26,14 @@ class TestCECMRegression(unittest.TestCase): def test_cecm(self): """ Integral regression test of integrator algorithm using CE/CM. """ - settings = opendeplete.Settings() + settings = openmc.deplete.Settings() settings.dt_vec = [0.75, 0.75] settings.output_dir = self.results op = dummy_geometry.DummyGeometry(settings) # Perform simulation using the MCNPX/MCNP6 algorithm - opendeplete.cecm(op, print_out=False) + openmc.deplete.cecm(op, print_out=False) # Load the files res = results.read_results(settings.output_dir + "/results.h5") @@ -59,8 +59,8 @@ class TestCECMRegression(unittest.TestCase): os.chdir(cls.cwd) - opendeplete.comm.barrier() - if opendeplete.comm.rank == 0: + openmc.deplete.comm.barrier() + if openmc.deplete.comm.rank == 0: os.remove(os.path.join(cls.results, "results.h5")) os.rmdir(cls.results) diff --git a/tests/deplete_tests/test_cram.py b/tests/deplete_tests/test_cram.py index 2744adbf48..10f41fe2b6 100644 --- a/tests/deplete_tests/test_cram.py +++ b/tests/deplete_tests/test_cram.py @@ -4,8 +4,8 @@ import unittest import numpy as np import scipy.sparse as sp +from openmc.deplete.integrator import CRAM16, CRAM48 -from opendeplete.integrator import CRAM16, CRAM48 class TestCram(unittest.TestCase): """ Tests for cram.py diff --git a/tests/deplete_tests/test_depletion_chain.py b/tests/deplete_tests/test_depletion_chain.py index 216d1e68f7..06abbba0f6 100644 --- a/tests/deplete_tests/test_depletion_chain.py +++ b/tests/deplete_tests/test_depletion_chain.py @@ -5,8 +5,7 @@ import os import unittest import numpy as np - -from opendeplete import comm, depletion_chain, reaction_rates, nuclide +from openmc.deplete import comm, depletion_chain, reaction_rates, nuclide class TestDepletionChain(unittest.TestCase): diff --git a/tests/deplete_tests/test_full.py b/tests/deplete_tests/test_full.py index f9a6c7493d..88c409554c 100644 --- a/tests/deplete_tests/test_full.py +++ b/tests/deplete_tests/test_full.py @@ -2,13 +2,14 @@ import shutil import unittest +from os.path import join, dirname import numpy as np +import openmc.deplete +from openmc.deplete import results +from openmc.deplete import utilities -import opendeplete -from opendeplete import results -from opendeplete import utilities -import test.example_geometry as example_geometry +from . import example_geometry class TestFull(unittest.TestCase): @@ -40,7 +41,7 @@ class TestFull(unittest.TestCase): dt = np.repeat([dt1], N) # Create settings variable - settings = opendeplete.OpenMCSettings() + settings = openmc.deplete.OpenMCSettings() settings.chain_file = "chains/chain_simple.xml" settings.openmc_call = "openmc" @@ -60,16 +61,17 @@ class TestFull(unittest.TestCase): settings.dt_vec = dt settings.output_dir = "test_full" - op = opendeplete.OpenMCOperator(geometry, settings) + op = openmc.deplete.OpenMCOperator(geometry, settings) # Perform simulation using the predictor algorithm - opendeplete.integrator.predictor(op) + openmc.deplete.integrator.predictor(op) # Load the files res_test = results.read_results(settings.output_dir + "/results.h5") # Load the reference - res_old = results.read_results("test/test_reference.h5") + filename = join(dirname(__file__), 'test_reference.h5') + res_old = results.read_results(filename) # Assert same mats for mat in res_old[0].mat_to_ind: @@ -110,8 +112,8 @@ class TestFull(unittest.TestCase): def tearDown(self): """ Clean up files""" - opendeplete.comm.barrier() - if opendeplete.comm.rank == 0: + openmc.deplete.comm.barrier() + if openmc.deplete.comm.rank == 0: shutil.rmtree("test_full", ignore_errors=True) diff --git a/tests/deplete_tests/test_integrator.py b/tests/deplete_tests/test_integrator.py index 7e121ce167..9b4cbe7802 100644 --- a/tests/deplete_tests/test_integrator.py +++ b/tests/deplete_tests/test_integrator.py @@ -6,8 +6,7 @@ import unittest from unittest.mock import MagicMock import numpy as np - -from opendeplete import integrator, ReactionRates, results, comm +from openmc.deplete import integrator, ReactionRates, results, comm class TestIntegrator(unittest.TestCase): diff --git a/tests/deplete_tests/test_nuclide.py b/tests/deplete_tests/test_nuclide.py index c5439b2aa3..2d379030d8 100644 --- a/tests/deplete_tests/test_nuclide.py +++ b/tests/deplete_tests/test_nuclide.py @@ -3,7 +3,7 @@ import unittest import xml.etree.ElementTree as ET -from opendeplete import nuclide +from openmc.deplete import nuclide class TestNuclide(unittest.TestCase): diff --git a/tests/deplete_tests/test_predictor_regression.py b/tests/deplete_tests/test_predictor_regression.py index c72ae8a475..a41ca9ce79 100644 --- a/tests/deplete_tests/test_predictor_regression.py +++ b/tests/deplete_tests/test_predictor_regression.py @@ -4,11 +4,11 @@ import os import unittest import numpy as np +import openmc.deplete +from openmc.deplete import results +from openmc.deplete import utilities -import opendeplete -from opendeplete import results -from opendeplete import utilities -import test.dummy_geometry as dummy_geometry +from . import dummy_geometry class TestPredictorRegression(unittest.TestCase): """ Regression tests for opendeplete.integrator.predictor algorithm. @@ -25,14 +25,14 @@ class TestPredictorRegression(unittest.TestCase): def test_predictor(self): """ Integral regression test of integrator algorithm using CE/CM. """ - settings = opendeplete.Settings() + settings = openmc.deplete.Settings() settings.dt_vec = [0.75, 0.75] settings.output_dir = self.results op = dummy_geometry.DummyGeometry(settings) # Perform simulation using the predictor algorithm - opendeplete.predictor(op, print_out=False) + openmc.deplete.predictor(op, print_out=False) # Load the files res = results.read_results(settings.output_dir + "/results.h5") @@ -58,8 +58,8 @@ class TestPredictorRegression(unittest.TestCase): os.chdir(cls.cwd) - opendeplete.comm.barrier() - if opendeplete.comm.rank == 0: + openmc.deplete.comm.barrier() + if openmc.deplete.comm.rank == 0: os.remove(os.path.join(cls.results, "results.h5")) os.rmdir(cls.results) diff --git a/tests/deplete_tests/test_reaction_rates.py b/tests/deplete_tests/test_reaction_rates.py index 4821ec18cd..2139be16c2 100644 --- a/tests/deplete_tests/test_reaction_rates.py +++ b/tests/deplete_tests/test_reaction_rates.py @@ -2,7 +2,7 @@ import unittest -from opendeplete import reaction_rates +from openmc.deplete import reaction_rates class TestReactionRates(unittest.TestCase): diff --git a/tests/deplete_tests/test_utilities.py b/tests/deplete_tests/test_utilities.py index faa1a500b4..fb60df5b7d 100644 --- a/tests/deplete_tests/test_utilities.py +++ b/tests/deplete_tests/test_utilities.py @@ -1,11 +1,11 @@ """ Full system test suite. """ import unittest +from os.path import join, dirname import numpy as np - -from opendeplete import results -from opendeplete import utilities +from openmc.deplete import results +from openmc.deplete import utilities class TestUtilities(unittest.TestCase): @@ -19,7 +19,8 @@ class TestUtilities(unittest.TestCase): """ # Load the reference - res = results.read_results("test/test_reference.h5") + filename = join(dirname(__file__), 'test_reference.h5') + res = results.read_results(filename) x, y = utilities.evaluate_single_nuclide(res, "1", "Xe135") @@ -35,7 +36,8 @@ class TestUtilities(unittest.TestCase): """ # Load the reference - res = results.read_results("test/test_reference.h5") + filename = join(dirname(__file__), 'test_reference.h5') + res = results.read_results(filename) x, y = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") @@ -53,7 +55,8 @@ class TestUtilities(unittest.TestCase): """ # Load the reference - res = results.read_results("test/test_reference.h5") + filename = join(dirname(__file__), 'test_reference.h5') + res = results.read_results(filename) x, y = utilities.evaluate_eigenvalue(res) From 0a772252cc4c64295b25832555f397bc3e431007 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 14:51:36 -0600 Subject: [PATCH 104/212] Fix bug in openmc_tally_set_scores (for depletion reactions) --- src/tallies/tally_header.F90 | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/tallies/tally_header.F90 b/src/tallies/tally_header.F90 index 474e77d1ce..9604d2382a 100644 --- a/src/tallies/tally_header.F90 +++ b/src/tallies/tally_header.F90 @@ -732,8 +732,10 @@ contains integer :: MT character(C_CHAR), pointer :: string(:) character(len=:, kind=C_CHAR), allocatable :: score_ + logical :: depletion_rx err = E_UNASSIGNED + depletion_rx = .false. if (index >= 1 .and. index <= size(tallies)) then associate (t => tallies(index) % obj) if (allocated(t % score_bins)) deallocate(t % score_bins) @@ -757,10 +759,13 @@ contains t % score_bins(i) = SCORE_NU_SCATTER case ('(n,2n)') t % score_bins(i) = N_2N + depletion_rx = .true. case ('(n,3n)') t % score_bins(i) = N_3N + depletion_rx = .true. case ('(n,4n)') t % score_bins(i) = N_4N + depletion_rx = .true. case ('absorption') t % score_bins(i) = SCORE_ABSORPTION case ('fission', '18') @@ -829,8 +834,10 @@ contains t % score_bins(i) = N_NC case ('(n,gamma)') t % score_bins(i) = N_GAMMA + depletion_rx = .true. case ('(n,p)') t % score_bins(i) = N_P + depletion_rx = .true. case ('(n,d)') t % score_bins(i) = N_D case ('(n,t)') @@ -839,6 +846,7 @@ contains t % score_bins(i) = N_3HE case ('(n,a)') t % score_bins(i) = N_A + depletion_rx = .true. case ('(n,2a)') t % score_bins(i) = N_2A case ('(n,3a)') @@ -879,6 +887,7 @@ contains end do err = 0 + t % depletion_rx = depletion_rx end associate else err = E_OUT_OF_BOUNDS From 8549f22e1408dd6e87184746b833b82f50e07d66 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 15:42:00 -0600 Subject: [PATCH 105/212] Move depletion tests into normal regression/unit test directories --- tests/deplete_tests/__init__.py | 0 tests/{deplete_tests => }/dummy_geometry.py | 0 .../example_geometry.py | 0 .../test_deplete_full.py} | 0 .../test_deplete_utilities.py} | 0 .../test_reference.h5 | Bin .../test_deplete_atom_number.py} | 0 .../test_deplete_cecm.py} | 2 +- .../test_deplete_cram.py} | 0 .../test_deplete_integrator.py} | 0 .../test_deplete_nuclide.py} | 0 .../test_deplete_predictor.py} | 2 +- .../test_deplete_reaction.py} | 0 .../test_depletion_chain.py | 0 14 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 tests/deplete_tests/__init__.py rename tests/{deplete_tests => }/dummy_geometry.py (100%) rename tests/{deplete_tests => regression_tests}/example_geometry.py (100%) rename tests/{deplete_tests/test_full.py => regression_tests/test_deplete_full.py} (100%) rename tests/{deplete_tests/test_utilities.py => regression_tests/test_deplete_utilities.py} (100%) rename tests/{deplete_tests => regression_tests}/test_reference.h5 (100%) rename tests/{deplete_tests/test_atom_number.py => unit_tests/test_deplete_atom_number.py} (100%) rename tests/{deplete_tests/test_cecm_regression.py => unit_tests/test_deplete_cecm.py} (98%) rename tests/{deplete_tests/test_cram.py => unit_tests/test_deplete_cram.py} (100%) rename tests/{deplete_tests/test_integrator.py => unit_tests/test_deplete_integrator.py} (100%) rename tests/{deplete_tests/test_nuclide.py => unit_tests/test_deplete_nuclide.py} (100%) rename tests/{deplete_tests/test_predictor_regression.py => unit_tests/test_deplete_predictor.py} (98%) rename tests/{deplete_tests/test_reaction_rates.py => unit_tests/test_deplete_reaction.py} (100%) rename tests/{deplete_tests => unit_tests}/test_depletion_chain.py (100%) diff --git a/tests/deplete_tests/__init__.py b/tests/deplete_tests/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/deplete_tests/dummy_geometry.py b/tests/dummy_geometry.py similarity index 100% rename from tests/deplete_tests/dummy_geometry.py rename to tests/dummy_geometry.py diff --git a/tests/deplete_tests/example_geometry.py b/tests/regression_tests/example_geometry.py similarity index 100% rename from tests/deplete_tests/example_geometry.py rename to tests/regression_tests/example_geometry.py diff --git a/tests/deplete_tests/test_full.py b/tests/regression_tests/test_deplete_full.py similarity index 100% rename from tests/deplete_tests/test_full.py rename to tests/regression_tests/test_deplete_full.py diff --git a/tests/deplete_tests/test_utilities.py b/tests/regression_tests/test_deplete_utilities.py similarity index 100% rename from tests/deplete_tests/test_utilities.py rename to tests/regression_tests/test_deplete_utilities.py diff --git a/tests/deplete_tests/test_reference.h5 b/tests/regression_tests/test_reference.h5 similarity index 100% rename from tests/deplete_tests/test_reference.h5 rename to tests/regression_tests/test_reference.h5 diff --git a/tests/deplete_tests/test_atom_number.py b/tests/unit_tests/test_deplete_atom_number.py similarity index 100% rename from tests/deplete_tests/test_atom_number.py rename to tests/unit_tests/test_deplete_atom_number.py diff --git a/tests/deplete_tests/test_cecm_regression.py b/tests/unit_tests/test_deplete_cecm.py similarity index 98% rename from tests/deplete_tests/test_cecm_regression.py rename to tests/unit_tests/test_deplete_cecm.py index 0d6966c82c..34c3435a76 100644 --- a/tests/deplete_tests/test_cecm_regression.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -8,7 +8,7 @@ import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities -from . import dummy_geometry +from tests import dummy_geometry class TestCECMRegression(unittest.TestCase): diff --git a/tests/deplete_tests/test_cram.py b/tests/unit_tests/test_deplete_cram.py similarity index 100% rename from tests/deplete_tests/test_cram.py rename to tests/unit_tests/test_deplete_cram.py diff --git a/tests/deplete_tests/test_integrator.py b/tests/unit_tests/test_deplete_integrator.py similarity index 100% rename from tests/deplete_tests/test_integrator.py rename to tests/unit_tests/test_deplete_integrator.py diff --git a/tests/deplete_tests/test_nuclide.py b/tests/unit_tests/test_deplete_nuclide.py similarity index 100% rename from tests/deplete_tests/test_nuclide.py rename to tests/unit_tests/test_deplete_nuclide.py diff --git a/tests/deplete_tests/test_predictor_regression.py b/tests/unit_tests/test_deplete_predictor.py similarity index 98% rename from tests/deplete_tests/test_predictor_regression.py rename to tests/unit_tests/test_deplete_predictor.py index a41ca9ce79..6ad2007d9c 100644 --- a/tests/deplete_tests/test_predictor_regression.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -8,7 +8,7 @@ import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities -from . import dummy_geometry +from tests import dummy_geometry class TestPredictorRegression(unittest.TestCase): """ Regression tests for opendeplete.integrator.predictor algorithm. diff --git a/tests/deplete_tests/test_reaction_rates.py b/tests/unit_tests/test_deplete_reaction.py similarity index 100% rename from tests/deplete_tests/test_reaction_rates.py rename to tests/unit_tests/test_deplete_reaction.py diff --git a/tests/deplete_tests/test_depletion_chain.py b/tests/unit_tests/test_depletion_chain.py similarity index 100% rename from tests/deplete_tests/test_depletion_chain.py rename to tests/unit_tests/test_depletion_chain.py From 592fae536f31521d09bd68a80d465550e6b34978 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 16:17:12 -0600 Subject: [PATCH 106/212] Fix file locations for depletion tests. Convert regression ones to pytest --- tests/conftest.py | 11 ++ tests/regression_tests/test_deplete_full.py | 156 ++++++++---------- .../test_deplete_utilities.py | 107 +++++------- tests/unit_tests/conftest.py | 9 - tests/unit_tests/test_depletion_chain.py | 10 +- 5 files changed, 133 insertions(+), 160 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 422c036fb3..dc55e8e1e9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,5 @@ +import pytest + from tests.regression_tests import config as regression_config @@ -15,3 +17,12 @@ def pytest_configure(config): for opt in opts: if config.getoption(opt) is not None: regression_config[opt] = config.getoption(opt) + + +@pytest.fixture +def run_in_tmpdir(tmpdir): + orig = tmpdir.chdir() + try: + yield + finally: + orig.chdir() diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 88c409554c..78039abc7e 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -1,121 +1,105 @@ """ Full system test suite. """ +from math import floor import shutil import unittest -from os.path import join, dirname +from pathlib import Path import numpy as np import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities -from . import example_geometry +from .example_geometry import generate_problem -class TestFull(unittest.TestCase): - """ Full system test suite. +def test_full(run_in_tmpdir): + """Full system test suite. Runs an entire OpenMC simulation with depletion coupling and verifies that the outputs match a reference file. Sensitive to changes in OpenMC. + + This test runs a complete OpenMC simulation and tests the outputs. + It will take a while. """ - def test_full(self): - """ - This test runs a complete OpenMC simulation and tests the outputs. - It will take a while. - """ + n_rings = 2 + n_wedges = 4 - n_rings = 2 - n_wedges = 4 + # Load geometry from example + geometry, lower_left, upper_right = generate_problem(n_rings, n_wedges) - # Load geometry from example - geometry, lower_left, upper_right = \ - example_geometry.generate_problem(n_rings=n_rings, n_wedges=n_wedges) + # Create dt vector for 3 steps with 15 day timesteps + dt1 = 15.*24*60*60 # 15 days + dt2 = 1.5*30*24*60*60 # 1.5 months + N = floor(dt2/dt1) + dt = np.full(N, dt1) - # Create dt vector for 3 steps with 15 day timesteps - dt1 = 15*24*60*60 # 15 days - dt2 = 1.5*30*24*60*60 # 1.5 months - N = np.floor(dt2/dt1) + # Create settings variable + settings = openmc.deplete.OpenMCSettings() - dt = np.repeat([dt1], N) - # Create settings variable - settings = openmc.deplete.OpenMCSettings() + chain_file = str(Path(__file__).parents[2] / 'chains' / 'chain_simple.xml') + settings.chain_file = chain_file + settings.openmc_call = "openmc" + settings.openmc_npernode = 2 + settings.particles = 100 + settings.batches = 100 + settings.inactive = 40 + settings.lower_left = lower_left + settings.upper_right = upper_right + settings.entropy_dimension = [10, 10, 1] - settings.chain_file = "chains/chain_simple.xml" - settings.openmc_call = "openmc" - settings.openmc_npernode = 2 - settings.particles = 100 - settings.batches = 100 - settings.inactive = 40 - settings.lower_left = lower_left - settings.upper_right = upper_right - settings.entropy_dimension = [10, 10, 1] + settings.round_number = True + settings.constant_seed = 1 - settings.round_number = True - settings.constant_seed = 1 + joule_per_mev = 1.6021766208e-13 + settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO + settings.dt_vec = dt + settings.output_dir = "test_full" - joule_per_mev = 1.6021766208e-13 - settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO - settings.dt_vec = dt - settings.output_dir = "test_full" + op = openmc.deplete.OpenMCOperator(geometry, settings) - op = openmc.deplete.OpenMCOperator(geometry, settings) + # Perform simulation using the predictor algorithm + openmc.deplete.integrator.predictor(op) - # Perform simulation using the predictor algorithm - openmc.deplete.integrator.predictor(op) + # Load the files + res_test = results.read_results(settings.output_dir + "/results.h5") - # Load the files - res_test = results.read_results(settings.output_dir + "/results.h5") + # Load the reference + filename = str(Path(__file__).with_name('test_reference.h5')) + res_old = results.read_results(filename) - # Load the reference - filename = join(dirname(__file__), 'test_reference.h5') - res_old = results.read_results(filename) + # Assert same mats + for mat in res_old[0].mat_to_ind: + assert mat in res_test[0].mat_to_ind, \ + "Material {} not in new results.".format(mat) + for nuc in res_old[0].nuc_to_ind: + assert nuc in res_test[0].nuc_to_ind, \ + "Nuclide {} not in new results.".format(nuc) - # Assert same mats - for mat in res_old[0].mat_to_ind: - self.assertIn(mat, res_test[0].mat_to_ind, - msg="Cell " + mat + " not in new results.") - for nuc in res_old[0].nuc_to_ind: - self.assertIn(nuc, res_test[0].nuc_to_ind, - msg="Nuclide " + nuc + " not in new results.") + for mat in res_test[0].mat_to_ind: + assert mat in res_old[0].mat_to_ind, \ + "Material {} not in old results.".format(mat) + for nuc in res_test[0].nuc_to_ind: + assert nuc in res_old[0].nuc_to_ind, \ + "Nuclide {} not in old results.".format(nuc) - for mat in res_test[0].mat_to_ind: - self.assertIn(mat, res_old[0].mat_to_ind, - msg="Cell " + mat + " not in old results.") + tol = 1.0e-6 + for mat in res_test[0].mat_to_ind: for nuc in res_test[0].nuc_to_ind: - self.assertIn(nuc, res_old[0].nuc_to_ind, - msg="Nuclide " + nuc + " not in old results.") + _, y_test = utilities.evaluate_single_nuclide(res_test, mat, nuc) + _, y_old = utilities.evaluate_single_nuclide(res_old, mat, nuc) - for mat in res_test[0].mat_to_ind: - for nuc in res_test[0].nuc_to_ind: - _, y_test = utilities.evaluate_single_nuclide(res_test, mat, nuc) - _, y_old = utilities.evaluate_single_nuclide(res_old, mat, nuc) + # Test each point + correct = True + for i, ref in enumerate(y_old): + if ref != y_test[i]: + if ref != 0.0: + correct = np.abs(y_test[i] - ref) / ref <= tol + else: + correct = False - # Test each point - - tol = 1.0e-6 - - correct = True - for i, ref in enumerate(y_old): - if ref != y_test[i]: - if ref != 0.0: - if np.abs(y_test[i] - ref) / ref > tol: - correct = False - else: - correct = False - - self.assertTrue(correct, - msg="Discrepancy in mat " + mat + " and nuc " + nuc - + "\n" + str(y_old) + "\n" + str(y_test)) - - def tearDown(self): - """ Clean up files""" - openmc.deplete.comm.barrier() - if openmc.deplete.comm.rank == 0: - shutil.rmtree("test_full", ignore_errors=True) - - -if __name__ == '__main__': - unittest.main() + assert correct, "Discrepancy in mat {} and nuc {}\n{}\n{}".format( + mat, nuc, y_old, y_test) diff --git a/tests/regression_tests/test_deplete_utilities.py b/tests/regression_tests/test_deplete_utilities.py index fb60df5b7d..f9d34aa75a 100644 --- a/tests/regression_tests/test_deplete_utilities.py +++ b/tests/regression_tests/test_deplete_utilities.py @@ -1,71 +1,54 @@ -""" Full system test suite. """ +""" Tests the utilities classes. -import unittest -from os.path import join, dirname +This also tests the results read/write code. +""" + +from pathlib import Path import numpy as np +import pytest from openmc.deplete import results from openmc.deplete import utilities -class TestUtilities(unittest.TestCase): - """ Tests the utilities classes. - - This also tests the results read/write code. - """ - - def test_evaluate_single_nuclide(self): - """ Tests evaluating single nuclide utility code. - """ - - # Load the reference - filename = join(dirname(__file__), 'test_reference.h5') - res = results.read_results(filename) - - x, y = utilities.evaluate_single_nuclide(res, "1", "Xe135") - - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - y_ref = [6.6747328233649218e+08, 3.5519299354458244e+14, - 3.4599104054580338e+14, 3.3821165110278112e+14] - - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, y_ref) - - def test_evaluate_reaction_rate(self): - """ Tests evaluating reaction rate utility code. - """ - - # Load the reference - filename = join(dirname(__file__), 'test_reference.h5') - res = results.read_results(filename) - - x, y = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") - - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - xe_ref = np.array([6.6747328233649218e+08, 3.5519299354458244e+14, - 3.4599104054580338e+14, 3.3821165110278112e+14]) - r_ref = np.array([4.0643598574337784e-05, 4.1457730544386974e-05, - 3.4121248544056681e-05, 3.9204686657643301e-05]) - - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, xe_ref * r_ref) - - def test_evaluate_eigenvalue(self): - """ Tests evaluating eigenvalue - """ - - # Load the reference - filename = join(dirname(__file__), 'test_reference.h5') - res = results.read_results(filename) - - x, y = utilities.evaluate_eigenvalue(res) - - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - y_ref = [1.1921986054449838, 1.1712785643938586, 1.1927099024502694, 1.2269183590698847] - - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, y_ref) +@pytest.fixture +def res(): + """Load the reference results""" + filename = str(Path(__file__).with_name('test_reference.h5')) + return results.read_results(filename) -if __name__ == '__main__': - unittest.main() +def test_evaluate_single_nuclide(res): + """Tests evaluating single nuclide utility code.""" + x, y = utilities.evaluate_single_nuclide(res, "1", "Xe135") + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + y_ref = [6.6747328233649218e+08, 3.5519299354458244e+14, + 3.4599104054580338e+14, 3.3821165110278112e+14] + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, y_ref) + +def test_evaluate_reaction_rate(res): + """Tests evaluating reaction rate utility code.""" + x, y = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + xe_ref = np.array([6.6747328233649218e+08, 3.5519299354458244e+14, + 3.4599104054580338e+14, 3.3821165110278112e+14]) + r_ref = np.array([4.0643598574337784e-05, 4.1457730544386974e-05, + 3.4121248544056681e-05, 3.9204686657643301e-05]) + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, xe_ref * r_ref) + + +def test_evaluate_eigenvalue(res): + """Tests evaluating eigenvalue.""" + x, y = utilities.evaluate_eigenvalue(res) + + x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + y_ref = [1.1921986054449838, 1.1712785643938586, 1.1927099024502694, 1.2269183590698847] + + np.testing.assert_array_equal(x, x_ref) + np.testing.assert_array_equal(y, y_ref) diff --git a/tests/unit_tests/conftest.py b/tests/unit_tests/conftest.py index d618b85def..1434eaf3b4 100644 --- a/tests/unit_tests/conftest.py +++ b/tests/unit_tests/conftest.py @@ -2,15 +2,6 @@ import openmc import pytest -@pytest.fixture -def run_in_tmpdir(tmpdir): - orig = tmpdir.chdir() - try: - yield - finally: - orig.chdir() - - @pytest.fixture(scope='module') def uo2(): m = openmc.Material(material_id=100, name='UO2') diff --git a/tests/unit_tests/test_depletion_chain.py b/tests/unit_tests/test_depletion_chain.py index 06abbba0f6..de7180e881 100644 --- a/tests/unit_tests/test_depletion_chain.py +++ b/tests/unit_tests/test_depletion_chain.py @@ -3,11 +3,15 @@ from collections import OrderedDict import os import unittest +from pathlib import Path import numpy as np from openmc.deplete import comm, depletion_chain, reaction_rates, nuclide +_test_filename = str(Path(__file__).parents[2] / 'chains' / 'chain_test.xml') + + class TestDepletionChain(unittest.TestCase): """ Tests for DepletionChain class.""" @@ -38,7 +42,7 @@ class TestDepletionChain(unittest.TestCase): # the components external to depletion_chain.py are simple storage # types. - dep = depletion_chain.DepletionChain.xml_read("chains/chain_test.xml") + dep = depletion_chain.DepletionChain.xml_read(_test_filename) # Basic checks self.assertEqual(dep.n_nuclides, 3) @@ -124,7 +128,7 @@ class TestDepletionChain(unittest.TestCase): chain.nuclides = [A, B, C] chain.xml_write(filename) - original = open('chains/chain_test.xml', 'r').read() + original = open(_test_filename, 'r').read() chain_xml = open(filename, 'r').read() self.assertEqual(original, chain_xml) @@ -134,7 +138,7 @@ class TestDepletionChain(unittest.TestCase): """ Using chain_test, and a dummy reaction rate, compute the matrix. """ # Relies on test_xml_read passing. - dep = depletion_chain.DepletionChain.xml_read("chains/chain_test.xml") + dep = depletion_chain.DepletionChain.xml_read(_test_filename) cell_ind = {"10000": 0, "10001": 1} nuc_ind = {"A": 0, "B": 1, "C": 2} From 2e358a2ca474371298dbbbe954527a3bcd764f78 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 9 Feb 2018 16:48:32 -0600 Subject: [PATCH 107/212] Release resources properly from Operator class --- openmc/deplete/integrator/cecm.py | 3 +++ openmc/deplete/integrator/predictor.py | 3 +++ openmc/deplete/openmc_wrapper.py | 7 ++++--- tests/dummy_geometry.py | 3 +++ tests/unit_tests/test_capi.py | 2 +- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 4d9baebb2e..699ccc2033 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -131,3 +131,6 @@ def cecm(operator, print_out=True): # Return to origin os.chdir(dir_home) + + # Release resources + operator.finalize() diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 6c9d538fd6..7b41e66493 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -98,3 +98,6 @@ def predictor(operator, print_out=True): # Return to origin os.chdir(dir_home) + + # Release resources + operator.finalize() diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 05b5057d20..5955a5defd 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -219,9 +219,6 @@ class OpenMCOperator(Operator): # Create reaction rate tables self.initialize_reaction_rates() - def __del__(self): - openmc.capi.finalize() - def extract_mat_ids(self): """Extracts materials and assigns them to processes. @@ -475,6 +472,10 @@ class OpenMCOperator(Operator): # Return number density vector return self.total_density_list() + def finalize(self): + """Finalize a depletion simulation and release resources.""" + openmc.capi.finalize() + def _update_materials(self): """Updates material compositions in OpenMC on all processes.""" diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index 614cc726e3..ecdce567d6 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -21,6 +21,9 @@ class DummyGeometry(Operator): def __init__(self, settings): super().__init__(settings) + def finalize(self): + pass + @property def chain(self): return self diff --git a/tests/unit_tests/test_capi.py b/tests/unit_tests/test_capi.py index 618f54e4f9..8bc6c3d15c 100644 --- a/tests/unit_tests/test_capi.py +++ b/tests/unit_tests/test_capi.py @@ -1,4 +1,4 @@ -from collections import Mapping +from collections.abc import Mapping import os import numpy as np From 3b31892816831c72354ca8de457c4bbb1afa39e0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 12 Feb 2018 13:34:35 -0600 Subject: [PATCH 108/212] Make sure entropy/UFS mesh index get cleared during finalize --- src/api.F90 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/api.F90 b/src/api.F90 index f07e5e38a5..d79a32d945 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -121,6 +121,8 @@ contains energy_min_neutron = ZERO entropy_on = .false. gen_per_batch = 1 + index_entropy_mesh = -1 + index_ufs_mesh = -1 keff = ONE legendre_to_tabular = .true. legendre_to_tabular_points = 33 From ef99788ff47cd7ff75c06e61f514fc6fe516f913 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 06:37:17 -0600 Subject: [PATCH 109/212] Get rid of OpenMCSettings.openmc_call, which doesn't make sense anymore --- openmc/deplete/openmc_wrapper.py | 3 --- scripts/example_run.py | 3 --- tests/regression_tests/test_deplete_full.py | 2 -- 3 files changed, 8 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 5955a5defd..66de945cda 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -58,8 +58,6 @@ class OpenMCSettings(Settings): chain_file : str Path to the depletion chain xml file. Defaults to the environment variable "OPENDEPLETE_CHAIN" if it exists. - openmc_call : str - OpenMC executable path. Defaults to "openmc". particles : int Number of particles to simulate per batch. batches : int @@ -94,7 +92,6 @@ class OpenMCSettings(Settings): self.chain_file = os.environ["OPENDEPLETE_CHAIN"] except KeyError: self.chain_file = None - self.openmc_call = "openmc" self.particles = None self.batches = None self.inactive = None diff --git a/scripts/example_run.py b/scripts/example_run.py index 82d0883c3a..78d7dceddc 100644 --- a/scripts/example_run.py +++ b/scripts/example_run.py @@ -18,9 +18,6 @@ dt = np.repeat([dt1], N) # Create settings variable settings = openmc.deplete.OpenMCSettings() -settings.openmc_call = "openmc" -# An example for mpiexec: -# settings.openmc_call = ["mpiexec", "openmc"] settings.particles = 1000 settings.batches = 100 settings.inactive = 40 diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 78039abc7e..dda1501fbc 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -42,8 +42,6 @@ def test_full(run_in_tmpdir): chain_file = str(Path(__file__).parents[2] / 'chains' / 'chain_simple.xml') settings.chain_file = chain_file - settings.openmc_call = "openmc" - settings.openmc_npernode = 2 settings.particles = 100 settings.batches = 100 settings.inactive = 40 From 26852f79f478a67a45ff790a8af2502f01116233 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 07:22:16 -0600 Subject: [PATCH 110/212] Add tqdm to dependencies. Install mpi4py on Travis --- setup.py | 2 +- tools/ci/travis-install.sh | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 2a42dd65dd..ee11f414b6 100755 --- a/setup.py +++ b/setup.py @@ -57,7 +57,7 @@ kwargs = { # Required dependencies 'install_requires': [ 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', - 'pandas', 'lxml', 'uncertainties' + 'pandas', 'lxml', 'uncertainties', 'tqdm' ], # Optional dependencies diff --git a/tools/ci/travis-install.sh b/tools/ci/travis-install.sh index 4921534db9..2342cdadbc 100755 --- a/tools/ci/travis-install.sh +++ b/tools/ci/travis-install.sh @@ -14,10 +14,15 @@ pip install cython pip install --upgrade pytest # Pandas stopped supporting Python 3.4 with version 0.21 -if [[ "$TRAVIS_PYTHON_VERSION" == "3.4" ]]; then +if [[ $TRAVIS_PYTHON_VERSION == "3.4" ]]; then pip install pandas==0.20.3 fi +# Install mpi4py for MPI configurations +if [[ $MPI == 'y' ]]; then + pip install --no-binary=mpi4py mpi4py +fi + # Build and install OpenMC executable python tools/ci/travis-install.py From 43147b70eb62ce983443ee3f17ac7bee49b6dd60 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 10:17:30 -0600 Subject: [PATCH 111/212] Change xml_write -> export_to_xml, xml_read -> from_xml for consistency --- openmc/deplete/depletion_chain.py | 8 ++++---- openmc/deplete/nuclide.py | 4 ++-- openmc/deplete/openmc_wrapper.py | 2 +- scripts/make_chain.py | 2 +- tests/unit_tests/test_deplete_nuclide.py | 8 ++++---- tests/unit_tests/test_depletion_chain.py | 15 ++++++++------- 6 files changed, 20 insertions(+), 19 deletions(-) diff --git a/openmc/deplete/depletion_chain.py b/openmc/deplete/depletion_chain.py index af126035f6..9f6b7cfeda 100644 --- a/openmc/deplete/depletion_chain.py +++ b/openmc/deplete/depletion_chain.py @@ -317,7 +317,7 @@ class DepletionChain(object): return depl_chain @classmethod - def xml_read(cls, filename): + def from_xml(cls, filename): """Reads a depletion chain XML file. Parameters @@ -343,7 +343,7 @@ class DepletionChain(object): reaction_index = 0 for i, nuclide_elem in enumerate(root.findall('nuclide_table')): - nuc = Nuclide.xml_read(nuclide_elem) + nuc = Nuclide.from_xml(nuclide_elem) depl_chain.nuclide_dict[nuc.name] = i # Check for reaction paths @@ -356,7 +356,7 @@ class DepletionChain(object): return depl_chain - def xml_write(self, filename): + def export_to_xml(self, filename): """Writes a depletion chain XML file. Parameters @@ -368,7 +368,7 @@ class DepletionChain(object): root_elem = ET.Element('depletion') for nuclide in self.nuclides: - root_elem.append(nuclide.xml_write()) + root_elem.append(nuclide.to_xml_element()) tree = ET.ElementTree(root_elem) if _have_lxml: diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py index 1208a9b3c3..17cf4d9b8f 100644 --- a/openmc/deplete/nuclide.py +++ b/openmc/deplete/nuclide.py @@ -71,7 +71,7 @@ class Nuclide(object): return len(self.reactions) @classmethod - def xml_read(cls, element): + def from_xml(cls, element): """Read nuclide from an XML element. Parameters @@ -129,7 +129,7 @@ class Nuclide(object): return nuc - def xml_write(self): + def to_xml_element(self): """Write nuclide to XML element. Returns diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 66de945cda..88b4971222 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -186,7 +186,7 @@ class OpenMCOperator(Operator): self.burn_nuc_to_ind = None # Read depletion chain - self.chain = DepletionChain.xml_read(settings.chain_file) + self.chain = DepletionChain.from_xml(settings.chain_file) # Clear out OpenMC, create task lists, distribute if comm.rank == 0: diff --git a/scripts/make_chain.py b/scripts/make_chain.py index ccf4ef9b7b..e2b0a23405 100644 --- a/scripts/make_chain.py +++ b/scripts/make_chain.py @@ -53,7 +53,7 @@ def main(): neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) chain = openmc.deplete.DepletionChain.from_endf(decay_files, nfy_files, neutron_files) - chain.xml_write('chain_endfb71.xml') + chain.export_to_xml('chain_endfb71.xml') if __name__ == '__main__': diff --git a/tests/unit_tests/test_deplete_nuclide.py b/tests/unit_tests/test_deplete_nuclide.py index 2d379030d8..ebcabc5ca9 100644 --- a/tests/unit_tests/test_deplete_nuclide.py +++ b/tests/unit_tests/test_deplete_nuclide.py @@ -35,7 +35,7 @@ class TestNuclide(unittest.TestCase): self.assertEqual(nuc.n_reaction_paths, 3) - def test_xml_read(self): + def test_from_xml(self): """Test reading nuclide data from an XML element.""" data = """ @@ -58,7 +58,7 @@ class TestNuclide(unittest.TestCase): """ element = ET.fromstring(data) - u235 = nuclide.Nuclide.xml_read(element) + u235 = nuclide.Nuclide.from_xml(element) self.assertEqual(u235.decay_modes, [ nuclide.DecayTuple('sf', 'U235', 7.2e-11), @@ -77,7 +77,7 @@ class TestNuclide(unittest.TestCase): ('Xe138', 0.0481413)] }) - def test_xml_write(self): + def test_to_xml_element(self): """Test writing nuclide data to an XML element.""" C = nuclide.Nuclide() @@ -93,7 +93,7 @@ class TestNuclide(unittest.TestCase): ] C.yield_energies = [0.0253] C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} - element = C.xml_write() + element = C.to_xml_element() self.assertEqual(element.get("half_life"), "0.123") diff --git a/tests/unit_tests/test_depletion_chain.py b/tests/unit_tests/test_depletion_chain.py index de7180e881..ba9e32db47 100644 --- a/tests/unit_tests/test_depletion_chain.py +++ b/tests/unit_tests/test_depletion_chain.py @@ -36,13 +36,13 @@ class TestDepletionChain(unittest.TestCase): out a good way to unit-test this.""" pass - def test_xml_read(self): + def test_from_xml(self): """ Read chain_test.xml and ensure all values are correct. """ # Unfortunately, this routine touches a lot of the code, but most of # the components external to depletion_chain.py are simple storage # types. - dep = depletion_chain.DepletionChain.xml_read(_test_filename) + dep = depletion_chain.DepletionChain.from_xml(_test_filename) # Basic checks self.assertEqual(dep.n_nuclides, 3) @@ -93,11 +93,11 @@ class TestDepletionChain(unittest.TestCase): self.assertEqual(nuc.yield_data[0.0253], [("A", 0.0292737), ("B", 0.002566345)]) - def test_xml_write(self): + def test_export_to_xml(self): """Test writing a depletion chain to XML.""" # Prevent different MPI ranks from conflicting - filename = 'test%u.xml' % comm.rank + filename = 'test{}.xml'.format(comm.rank) A = nuclide.Nuclide() A.name = "A" @@ -126,7 +126,7 @@ class TestDepletionChain(unittest.TestCase): chain = depletion_chain.DepletionChain() chain.nuclides = [A, B, C] - chain.xml_write(filename) + chain.export_to_xml(filename) original = open(_test_filename, 'r').read() chain_xml = open(filename, 'r').read() @@ -136,9 +136,9 @@ class TestDepletionChain(unittest.TestCase): def test_form_matrix(self): """ Using chain_test, and a dummy reaction rate, compute the matrix. """ - # Relies on test_xml_read passing. + # Relies on test_from_xml passing. - dep = depletion_chain.DepletionChain.xml_read(_test_filename) + dep = depletion_chain.DepletionChain.from_xml(_test_filename) cell_ind = {"10000": 0, "10001": 1} nuc_ind = {"A": 0, "B": 1, "C": 2} @@ -196,5 +196,6 @@ class TestDepletionChain(unittest.TestCase): self.assertEqual("NucB", dep.nuc_by_ind("NucB")) self.assertEqual("NucC", dep.nuc_by_ind("NucC")) + if __name__ == '__main__': unittest.main() From 1ee27edc8c935f48894dbefb37bfe48f2db06583 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 10:45:39 -0600 Subject: [PATCH 112/212] Rename DepletionChain -> Chain --- docs/source/pythonapi/deplete/index.rst | 24 +++++++-------- .../pythonapi/deplete/integrator.CRAM16.rst | 2 +- .../pythonapi/deplete/integrator.CRAM48.rst | 2 +- .../pythonapi/deplete/integrator.cecm.rst | 2 +- .../deplete/integrator.predictor.rst | 2 +- .../deplete/integrator.save_results.rst | 2 +- .../deplete/opendeplete.Concentrations.rst | 30 ------------------- .../deplete/opendeplete.ReactionRates.rst | 30 ------------------- .../pythonapi/deplete/opendeplete.Results.rst | 22 -------------- openmc/data/data.py | 3 +- openmc/deplete/__init__.py | 2 +- .../deplete/{depletion_chain.py => chain.py} | 8 ++--- openmc/deplete/openmc_wrapper.py | 20 ++++++------- scripts/make_chain.py | 2 +- ...pletion_chain.py => test_deplete_chain.py} | 20 ++++++------- 15 files changed, 44 insertions(+), 127 deletions(-) delete mode 100644 docs/source/pythonapi/deplete/opendeplete.Concentrations.rst delete mode 100644 docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst delete mode 100644 docs/source/pythonapi/deplete/opendeplete.Results.rst rename openmc/deplete/{depletion_chain.py => chain.py} (99%) rename tests/unit_tests/{test_depletion_chain.py => test_deplete_chain.py} (92%) diff --git a/docs/source/pythonapi/deplete/index.rst b/docs/source/pythonapi/deplete/index.rst index 55380c7a1c..30d2d42611 100644 --- a/docs/source/pythonapi/deplete/index.rst +++ b/docs/source/pythonapi/deplete/index.rst @@ -17,7 +17,7 @@ Integrator Helper Functions --------------------------- .. toctree:: :maxdepth: 2 - + integrator.CRAM16 integrator.CRAM48 integrator.save_results @@ -29,8 +29,8 @@ Metaclasses :toctree: generated :nosignatures: - opendeplete.Settings - opendeplete.Operator + openmc.deplete.Settings + openmc.deplete.Operator OpenMC Classes -------------- @@ -39,18 +39,18 @@ OpenMC Classes :toctree: generated :nosignatures: - opendeplete.OpenMCSettings - opendeplete.Materials - opendeplete.OpenMCOperator + openmc.deplete.OpenMCSettings + openmc.deplete.Materials + openmc.deplete.OpenMCOperator Data Classes ------------ .. autosummary:: :toctree: generated :nosignatures: - - opendeplete.AtomNumber - opendeplete.DepletionChain - opendeplete.Nuclide - opendeplete.ReactionRates - opendeplete.Results + + openmc.deplete.AtomNumber + openmc.deplete.Chain + openmc.deplete.Nuclide + openmc.deplete.ReactionRates + openmc.deplete.Results diff --git a/docs/source/pythonapi/deplete/integrator.CRAM16.rst b/docs/source/pythonapi/deplete/integrator.CRAM16.rst index f9eba273ed..a0dc648056 100644 --- a/docs/source/pythonapi/deplete/integrator.CRAM16.rst +++ b/docs/source/pythonapi/deplete/integrator.CRAM16.rst @@ -1,6 +1,6 @@ integrator\.CRAM16 ================== -.. currentmodule:: opendeplete.integrator +.. currentmodule:: openmc.deplete.integrator .. autofunction:: CRAM16 diff --git a/docs/source/pythonapi/deplete/integrator.CRAM48.rst b/docs/source/pythonapi/deplete/integrator.CRAM48.rst index d7467a418a..f9720f7ad9 100644 --- a/docs/source/pythonapi/deplete/integrator.CRAM48.rst +++ b/docs/source/pythonapi/deplete/integrator.CRAM48.rst @@ -1,6 +1,6 @@ integrator\.CRAM48 ================== -.. currentmodule:: opendeplete.integrator +.. currentmodule:: openmc.deplete.integrator .. autofunction:: CRAM48 diff --git a/docs/source/pythonapi/deplete/integrator.cecm.rst b/docs/source/pythonapi/deplete/integrator.cecm.rst index 507a638f69..4851b20b34 100644 --- a/docs/source/pythonapi/deplete/integrator.cecm.rst +++ b/docs/source/pythonapi/deplete/integrator.cecm.rst @@ -1,6 +1,6 @@ integrator\.cecm ================= -.. currentmodule:: opendeplete.integrator +.. currentmodule:: openmc.deplete.integrator .. autofunction:: cecm diff --git a/docs/source/pythonapi/deplete/integrator.predictor.rst b/docs/source/pythonapi/deplete/integrator.predictor.rst index d6c0fd827c..2243e77f71 100644 --- a/docs/source/pythonapi/deplete/integrator.predictor.rst +++ b/docs/source/pythonapi/deplete/integrator.predictor.rst @@ -1,6 +1,6 @@ integrator\.predictor ===================== -.. currentmodule:: opendeplete.integrator +.. currentmodule:: openmc.deplete.integrator .. autofunction:: predictor diff --git a/docs/source/pythonapi/deplete/integrator.save_results.rst b/docs/source/pythonapi/deplete/integrator.save_results.rst index 5c21dcb664..f9c830cd5b 100644 --- a/docs/source/pythonapi/deplete/integrator.save_results.rst +++ b/docs/source/pythonapi/deplete/integrator.save_results.rst @@ -1,6 +1,6 @@ integrator\.save_results ======================== -.. currentmodule:: opendeplete.integrator +.. currentmodule:: openmc.deplete.integrator .. autofunction:: save_results diff --git a/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst b/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst deleted file mode 100644 index 6fa07a970b..0000000000 --- a/docs/source/pythonapi/deplete/opendeplete.Concentrations.rst +++ /dev/null @@ -1,30 +0,0 @@ -opendeplete.Concentrations -========================== - -.. currentmodule:: opendeplete - -.. autoclass:: Concentrations - - - .. automethod:: __init__ - - - .. rubric:: Methods - - .. autosummary:: - - ~Concentrations.__init__ - ~Concentrations.convert_nested_dict - - - - - - .. rubric:: Attributes - - .. autosummary:: - - ~Concentrations.n_cell - ~Concentrations.n_nuc - - \ No newline at end of file diff --git a/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst b/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst deleted file mode 100644 index 99e048b565..0000000000 --- a/docs/source/pythonapi/deplete/opendeplete.ReactionRates.rst +++ /dev/null @@ -1,30 +0,0 @@ -opendeplete.ReactionRates -========================= - -.. currentmodule:: opendeplete - -.. autoclass:: ReactionRates - - - .. automethod:: __init__ - - - .. rubric:: Methods - - .. autosummary:: - - ~ReactionRates.__init__ - - - - - - .. rubric:: Attributes - - .. autosummary:: - - ~ReactionRates.n_cell - ~ReactionRates.n_nuc - ~ReactionRates.n_react - - \ No newline at end of file diff --git a/docs/source/pythonapi/deplete/opendeplete.Results.rst b/docs/source/pythonapi/deplete/opendeplete.Results.rst deleted file mode 100644 index 0ab8a1f711..0000000000 --- a/docs/source/pythonapi/deplete/opendeplete.Results.rst +++ /dev/null @@ -1,22 +0,0 @@ -opendeplete.Results -=================== - -.. currentmodule:: opendeplete - -.. autoclass:: Results - - - .. automethod:: __init__ - - - .. rubric:: Methods - - .. autosummary:: - - ~Results.__init__ - - - - - - \ No newline at end of file diff --git a/openmc/data/data.py b/openmc/data/data.py index a7c0e536f6..523ac9769d 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -319,8 +319,9 @@ def water_density(temperature, pressure=0.1013): # The value of the Boltzman constant in units of eV / K K_BOLTZMANN = 8.6173303e-5 -# Used for converting units in ACE data +# Unit conversions EV_PER_MEV = 1.0e6 +JOULE_PER_EV = 1.6021766208e-19 # Avogadro's constant AVOGADRO = 6.022140857e23 diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py index 4bdde3935e..19d1d13201 100644 --- a/openmc/deplete/__init__.py +++ b/openmc/deplete/__init__.py @@ -15,7 +15,7 @@ except ImportError: have_mpi = False from .nuclide import * -from .depletion_chain import * +from .chain import * from .openmc_wrapper import * from .reaction_rates import * from .function import * diff --git a/openmc/deplete/depletion_chain.py b/openmc/deplete/chain.py similarity index 99% rename from openmc/deplete/depletion_chain.py rename to openmc/deplete/chain.py index 9f6b7cfeda..03decb72ab 100644 --- a/openmc/deplete/depletion_chain.py +++ b/openmc/deplete/chain.py @@ -1,4 +1,4 @@ -"""depletion_chain module. +"""chain module. This module contains information about a depletion chain. A depletion chain is loaded from an .xml file and all the nuclides are linked together. @@ -108,10 +108,8 @@ def replace_missing(product, decay_data): return product -class DepletionChain(object): - """The DepletionChain class. - - This class contains a full representation of a depletion chain. +class Chain(object): + """Full representation of a depletion chain. Attributes ---------- diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 88b4971222..5c7a1aebaa 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -21,14 +21,14 @@ import numpy as np import openmc import openmc.capi +from openmc.data import JOULE_PER_EV from . import comm from .atom_number import AtomNumber -from .depletion_chain import DepletionChain +from .chain import Chain from .reaction_rates import ReactionRates from .function import Settings, Operator -_JOULE_PER_EV = 1.6021766208e-19 def chunks(items, n): @@ -149,13 +149,13 @@ class OpenMCOperator(Operator): Materials to be used for this simulation. seed : int The RNG seed used in last OpenMC run. - number : AtomNumber + number : openmc.deplete.AtomNumber Total number of atoms in simulation. participating_nuclides : set of str A set listing all unique nuclides available from cross_sections.xml. - chain : DepletionChain + chain : openmc.deplete.Chain The depletion chain information necessary to form matrices and tallies. - reaction_rates : ReactionRates + reaction_rates : openmc.deplete.ReactionRates Reaction rates from the last operator step. power : OrderedDict of str to float Material-by-Material power. Indexed by material ID. @@ -186,7 +186,7 @@ class OpenMCOperator(Operator): self.burn_nuc_to_ind = None # Read depletion chain - self.chain = DepletionChain.from_xml(settings.chain_file) + self.chain = Chain.from_xml(settings.chain_file) # Clear out OpenMC, create task lists, distribute if comm.rank == 0: @@ -390,7 +390,7 @@ class OpenMCOperator(Operator): Matrices for the next step. k : float Eigenvalue of the problem. - rates : ReactionRates + rates : openmc.deplete.ReactionRates Reaction rates from this simulation. seed : int Seed for this simulation. @@ -602,11 +602,11 @@ class OpenMCOperator(Operator): def generate_tallies(self): """Generates depletion tallies. - Using information from self.depletion_chain as well as the nuclides + Using information from the depletion chain as well as the nuclides currently in the problem, this function automatically generates a tally.xml for the simulation. - """ + """ # Create tallies for depleting regions materials = [openmc.capi.materials[int(i)] for i in self.mat_tally_ind] @@ -742,7 +742,7 @@ class OpenMCOperator(Operator): energy = comm.allreduce(energy) # Determine power in eV/s - power = self.settings.power / _JOULE_PER_EV + power = self.settings.power / JOULE_PER_EV # Scale reaction rates to obtain units of reactions/sec rates[:, :, :] *= power / energy diff --git a/scripts/make_chain.py b/scripts/make_chain.py index e2b0a23405..6d64f34b3c 100644 --- a/scripts/make_chain.py +++ b/scripts/make_chain.py @@ -52,7 +52,7 @@ def main(): nfy_files = glob.glob(os.path.join('nfy', '*.endf')) neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) - chain = openmc.deplete.DepletionChain.from_endf(decay_files, nfy_files, neutron_files) + chain = openmc.deplete.Chain.from_endf(decay_files, nfy_files, neutron_files) chain.export_to_xml('chain_endfb71.xml') diff --git a/tests/unit_tests/test_depletion_chain.py b/tests/unit_tests/test_deplete_chain.py similarity index 92% rename from tests/unit_tests/test_depletion_chain.py rename to tests/unit_tests/test_deplete_chain.py index ba9e32db47..6166f15612 100644 --- a/tests/unit_tests/test_depletion_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -1,4 +1,4 @@ -""" Tests for depletion_chain.py""" +"""Tests for depletion chains""" from collections import OrderedDict import os @@ -6,18 +6,18 @@ import unittest from pathlib import Path import numpy as np -from openmc.deplete import comm, depletion_chain, reaction_rates, nuclide +from openmc.deplete import comm, Chain, reaction_rates, nuclide _test_filename = str(Path(__file__).parents[2] / 'chains' / 'chain_test.xml') -class TestDepletionChain(unittest.TestCase): - """ Tests for DepletionChain class.""" +class TestChain(unittest.TestCase): + """ Tests for Chain class.""" def test__init__(self): """ Test depletion chain initialization.""" - dep = depletion_chain.DepletionChain() + dep = Chain() self.assertIsInstance(dep.nuclides, list) self.assertIsInstance(dep.nuclide_dict, OrderedDict) @@ -25,7 +25,7 @@ class TestDepletionChain(unittest.TestCase): def test_n_nuclides(self): """ Test depletion chain n_nuclides parameter. """ - dep = depletion_chain.DepletionChain() + dep = Chain() dep.nuclides = ["NucA", "NucB", "NucC"] @@ -42,7 +42,7 @@ class TestDepletionChain(unittest.TestCase): # the components external to depletion_chain.py are simple storage # types. - dep = depletion_chain.DepletionChain.from_xml(_test_filename) + dep = Chain.from_xml(_test_filename) # Basic checks self.assertEqual(dep.n_nuclides, 3) @@ -124,7 +124,7 @@ class TestDepletionChain(unittest.TestCase): C.yield_energies = [0.0253] C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} - chain = depletion_chain.DepletionChain() + chain = Chain() chain.nuclides = [A, B, C] chain.export_to_xml(filename) @@ -138,7 +138,7 @@ class TestDepletionChain(unittest.TestCase): """ Using chain_test, and a dummy reaction rate, compute the matrix. """ # Relies on test_from_xml passing. - dep = depletion_chain.DepletionChain.from_xml(_test_filename) + dep = Chain.from_xml(_test_filename) cell_ind = {"10000": 0, "10001": 1} nuc_ind = {"A": 0, "B": 1, "C": 2} @@ -187,7 +187,7 @@ class TestDepletionChain(unittest.TestCase): def test_nuc_by_ind(self): """ Test nuc_by_ind converter function. """ - dep = depletion_chain.DepletionChain() + dep = Chain() dep.nuclides = ["NucA", "NucB", "NucC"] dep.nuclide_dict = {"NucA" : 0, "NucB" : 1, "NucC" : 2} From dba919c6109009670cc41decae356588c47c305f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 11:24:24 -0600 Subject: [PATCH 113/212] Convert deplete unit tests to use pytest --- openmc/deplete/integrator/cram.py | 4 +- openmc/deplete/results.py | 2 +- tests/regression_tests/test_deplete_full.py | 1 - tests/unit_tests/test_deplete_atom_number.py | 321 ++++++++-------- tests/unit_tests/test_deplete_cecm.py | 75 ++-- tests/unit_tests/test_deplete_chain.py | 367 +++++++++---------- tests/unit_tests/test_deplete_cram.py | 61 ++- tests/unit_tests/test_deplete_integrator.py | 156 ++++---- tests/unit_tests/test_deplete_nuclide.py | 165 ++++----- tests/unit_tests/test_deplete_predictor.py | 74 ++-- tests/unit_tests/test_deplete_reaction.py | 140 ++++--- 11 files changed, 631 insertions(+), 735 deletions(-) diff --git a/openmc/deplete/integrator/cram.py b/openmc/deplete/integrator/cram.py index a18d8450c3..56476384c6 100644 --- a/openmc/deplete/integrator/cram.py +++ b/openmc/deplete/integrator/cram.py @@ -1,6 +1,6 @@ -""" Chebyshev Rational Approximation Method module +"""Chebyshev Rational Approximation Method module -Implements two different forms of CRAM for use in opendeplete. +Implements two different forms of CRAM for use in openmc.deplete. """ import numpy as np diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index ae096b8ce5..c08b3ef40d 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -16,7 +16,7 @@ RESULTS_VERSION = 2 class Results(object): - """Contains output of opendeplete. + """Contains output of a depletion run. Attributes ---------- diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index dda1501fbc..5f4af7a737 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -2,7 +2,6 @@ from math import floor import shutil -import unittest from pathlib import Path import numpy as np diff --git a/tests/unit_tests/test_deplete_atom_number.py b/tests/unit_tests/test_deplete_atom_number.py index d36b96d38d..e3eb22aa55 100644 --- a/tests/unit_tests/test_deplete_atom_number.py +++ b/tests/unit_tests/test_deplete_atom_number.py @@ -1,180 +1,177 @@ -""" Tests for atom_number.py. """ - -import unittest +""" Tests for the AtomNumber class """ import numpy as np from openmc.deplete import atom_number -class TestAtomNumber(unittest.TestCase): - """Tests for the AtomNumber class.""" +def test_indexing(): + """Tests the __getitem__ and __setitem__ routines simultaneously.""" - def test_indexing(self): - """Tests the __getitem__ and __setitem__ routines simultaneously.""" + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number["10000", "U238"] = 1.0 + number["10001", "U238"] = 2.0 + number["10000", "U235"] = 3.0 + number["10001", "U235"] = 4.0 - number["10000", "U238"] = 1.0 - number["10001", "U238"] = 2.0 - number["10000", "U235"] = 3.0 - number["10001", "U235"] = 4.0 + # String indexing + assert number["10000", "U238"] == 1.0 + assert number["10001", "U238"] == 2.0 + assert number["10000", "U235"] == 3.0 + assert number["10001", "U235"] == 4.0 - # String indexing - self.assertEqual(number["10000", "U238"], 1.0) - self.assertEqual(number["10001", "U238"], 2.0) - self.assertEqual(number["10000", "U235"], 3.0) - self.assertEqual(number["10001", "U235"], 4.0) + # Int indexing + assert number[0, 0] == 1.0 + assert number[1, 0] == 2.0 + assert number[0, 1] == 3.0 + assert number[1, 1] == 4.0 - # Int indexing - self.assertEqual(number[0, 0], 1.0) - self.assertEqual(number[1, 0], 2.0) - self.assertEqual(number[0, 1], 3.0) - self.assertEqual(number[1, 1], 4.0) + number[0, 0] = 5.0 - number[0, 0] = 5.0 - - self.assertEqual(number[0, 0], 5.0) - self.assertEqual(number["10000", "U238"], 5.0) - - def test_n_mat(self): - """Test number of materials property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - self.assertEqual(number.n_mat, 2) - - def test_n_nuc(self): - """Test number of nuclides property.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - self.assertEqual(number.n_nuc, 3) - - def test_burn_nuc_list(self): - """Test the list of burned nuclides property""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - self.assertEqual(number.burn_nuc_list, ["U238", "U235"]) - - def test_burn_mat_list(self): - """Test the list of burned nuclides property""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - self.assertEqual(number.burn_mat_list, ["10000", "10001"]) - - def test_density_indexing(self): - """Tests the get and set_atom_density routines simultaneously.""" - - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - number.set_atom_density("10000", "U238", 1.0) - number.set_atom_density("10001", "U238", 2.0) - number.set_atom_density("10002", "U238", 3.0) - number.set_atom_density("10000", "U235", 4.0) - number.set_atom_density("10001", "U235", 5.0) - number.set_atom_density("10002", "U235", 6.0) - number.set_atom_density("10000", "U234", 7.0) - number.set_atom_density("10001", "U234", 8.0) - number.set_atom_density("10002", "U234", 9.0) - - # String indexing - self.assertEqual(number.get_atom_density("10000", "U238"), 1.0) - self.assertEqual(number.get_atom_density("10001", "U238"), 2.0) - self.assertEqual(number.get_atom_density("10002", "U238"), 3.0) - self.assertEqual(number.get_atom_density("10000", "U235"), 4.0) - self.assertEqual(number.get_atom_density("10001", "U235"), 5.0) - self.assertEqual(number.get_atom_density("10002", "U235"), 6.0) - self.assertEqual(number.get_atom_density("10000", "U234"), 7.0) - self.assertEqual(number.get_atom_density("10001", "U234"), 8.0) - self.assertEqual(number.get_atom_density("10002", "U234"), 9.0) - - # Int indexing - self.assertEqual(number.get_atom_density(0, 0), 1.0) - self.assertEqual(number.get_atom_density(1, 0), 2.0) - self.assertEqual(number.get_atom_density(2, 0), 3.0) - self.assertEqual(number.get_atom_density(0, 1), 4.0) - self.assertEqual(number.get_atom_density(1, 1), 5.0) - self.assertEqual(number.get_atom_density(2, 1), 6.0) - self.assertEqual(number.get_atom_density(0, 2), 7.0) - self.assertEqual(number.get_atom_density(1, 2), 8.0) - self.assertEqual(number.get_atom_density(2, 2), 9.0) + assert number[0, 0] == 5.0 + assert number["10000", "U238"] == 5.0 - number.set_atom_density(0, 0, 5.0) +def test_n_mat(): + """Test number of materials property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} - self.assertEqual(number.get_atom_density(0, 0), 5.0) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - # Verify volume is used correctly - self.assertEqual(number[0, 0], 5.0 * 0.38) - self.assertEqual(number[1, 0], 2.0 * 0.21) - self.assertEqual(number[2, 0], 3.0 * 1.0) - self.assertEqual(number[0, 1], 4.0 * 0.38) - self.assertEqual(number[1, 1], 5.0 * 0.21) - self.assertEqual(number[2, 1], 6.0 * 1.0) - self.assertEqual(number[0, 2], 7.0 * 0.38) - self.assertEqual(number[1, 2], 8.0 * 0.21) - self.assertEqual(number[2, 2], 9.0 * 1.0) - - def test_get_mat_slice(self): - """Tests getting slices.""" - - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) - - sl = number.get_mat_slice(0) - - np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) - - sl = number.get_mat_slice("10000") - - np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) - - def test_set_mat_slice(self): - """Tests getting slices.""" - - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - number.set_mat_slice(0, [1.0, 2.0]) - - self.assertEqual(number[0, 0], 1.0) - self.assertEqual(number[0, 1], 2.0) - - number.set_mat_slice("10000", [3.0, 4.0]) - - self.assertEqual(number[0, 0], 3.0) - self.assertEqual(number[0, 1], 4.0) + assert number.n_mat == 2 -if __name__ == '__main__': - unittest.main() +def test_n_nuc(): + """Test number of nuclides property.""" + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + assert number.n_nuc == 3 + + +def test_burn_nuc_list(): + """Test the list of burned nuclides property""" + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + assert number.burn_nuc_list == ["U238", "U235"] + + +def test_burn_mat_list(): + """Test the list of burned nuclides property""" + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + assert number.burn_mat_list == ["10000", "10001"] + + +def test_density_indexing(): + """Tests the get and set_atom_density routines simultaneously.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.set_atom_density("10000", "U238", 1.0) + number.set_atom_density("10001", "U238", 2.0) + number.set_atom_density("10002", "U238", 3.0) + number.set_atom_density("10000", "U235", 4.0) + number.set_atom_density("10001", "U235", 5.0) + number.set_atom_density("10002", "U235", 6.0) + number.set_atom_density("10000", "U234", 7.0) + number.set_atom_density("10001", "U234", 8.0) + number.set_atom_density("10002", "U234", 9.0) + + # String indexing + assert number.get_atom_density("10000", "U238") == 1.0 + assert number.get_atom_density("10001", "U238") == 2.0 + assert number.get_atom_density("10002", "U238") == 3.0 + assert number.get_atom_density("10000", "U235") == 4.0 + assert number.get_atom_density("10001", "U235") == 5.0 + assert number.get_atom_density("10002", "U235") == 6.0 + assert number.get_atom_density("10000", "U234") == 7.0 + assert number.get_atom_density("10001", "U234") == 8.0 + assert number.get_atom_density("10002", "U234") == 9.0 + + # Int indexing + assert number.get_atom_density(0, 0) == 1.0 + assert number.get_atom_density(1, 0) == 2.0 + assert number.get_atom_density(2, 0) == 3.0 + assert number.get_atom_density(0, 1) == 4.0 + assert number.get_atom_density(1, 1) == 5.0 + assert number.get_atom_density(2, 1) == 6.0 + assert number.get_atom_density(0, 2) == 7.0 + assert number.get_atom_density(1, 2) == 8.0 + assert number.get_atom_density(2, 2) == 9.0 + + + number.set_atom_density(0, 0, 5.0) + assert number.get_atom_density(0, 0) == 5.0 + + # Verify volume is used correctly + assert number[0, 0] == 5.0 * 0.38 + assert number[1, 0] == 2.0 * 0.21 + assert number[2, 0] == 3.0 * 1.0 + assert number[0, 1] == 4.0 * 0.38 + assert number[1, 1] == 5.0 * 0.21 + assert number[2, 1] == 6.0 * 1.0 + assert number[0, 2] == 7.0 * 0.38 + assert number[1, 2] == 8.0 * 0.21 + assert number[2, 2] == 9.0 * 1.0 + + +def test_get_mat_slice(): + """Tests getting slices.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) + + sl = number.get_mat_slice(0) + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + sl = number.get_mat_slice("10000") + + np.testing.assert_array_equal(sl, np.array([1.0, 2.0])) + + +def test_set_mat_slice(): + """Tests getting slices.""" + + mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + volume = {"10000" : 0.38, "10001" : 0.21} + + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + + number.set_mat_slice(0, [1.0, 2.0]) + + assert number[0, 0] == 1.0 + assert number[0, 1] == 2.0 + + number.set_mat_slice("10000", [3.0, 4.0]) + + assert number[0, 0] == 3.0 + assert number[0, 1] == 4.0 diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 34c3435a76..264ad21671 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -1,9 +1,9 @@ -""" Regression tests for cecm.py""" +"""Regression tests for openmc.deplete.integrator.cecm algorithm. -import os -import unittest +These tests integrate a simple test problem described in dummy_geometry.py. +""" -import numpy as np +from pytest import approx import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities @@ -11,59 +11,30 @@ from openmc.deplete import utilities from tests import dummy_geometry -class TestCECMRegression(unittest.TestCase): - """ Regression tests for opendeplete.integrator.cecm algorithm. +def test_cecm(run_in_tmpdir): + """Integral regression test of integrator algorithm using CE/CM.""" - These tests integrate a simple test problem described in dummy_geometry.py. - """ + settings = openmc.deplete.Settings() + settings.dt_vec = [0.75, 0.75] + settings.output_dir = "test_integrator_regression" - @classmethod - def setUpClass(cls): - """ Save current directory in case integrator crashes.""" - cls.cwd = os.getcwd() - cls.results = "test_integrator_regression" + op = dummy_geometry.DummyGeometry(settings) - def test_cecm(self): - """ Integral regression test of integrator algorithm using CE/CM. """ + # Perform simulation using the MCNPX/MCNP6 algorithm + openmc.deplete.cecm(op, print_out=False) - settings = openmc.deplete.Settings() - settings.dt_vec = [0.75, 0.75] - settings.output_dir = self.results + # Load the files + res = results.read_results(settings.output_dir + "/results.h5") - op = dummy_geometry.DummyGeometry(settings) + _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") + _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") - # Perform simulation using the MCNPX/MCNP6 algorithm - openmc.deplete.cecm(op, print_out=False) + # Mathematica solution + s1 = [1.86872629872102, 1.395525772416039] + s2 = [2.18097439443550, 2.69429754646747] - # Load the files - res = results.read_results(settings.output_dir + "/results.h5") + assert y1[1] == approx(s1[0]) + assert y2[1] == approx(s1[1]) - _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") - _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") - - # Mathematica solution - s1 = [1.86872629872102, 1.395525772416039] - s2 = [2.18097439443550, 2.69429754646747] - - tol = 1.0e-13 - - self.assertLess(np.absolute(y1[1] - s1[0]), tol) - self.assertLess(np.absolute(y2[1] - s1[1]), tol) - - self.assertLess(np.absolute(y1[2] - s2[0]), tol) - self.assertLess(np.absolute(y2[2] - s2[1]), tol) - - @classmethod - def tearDownClass(cls): - """ Clean up files""" - - os.chdir(cls.cwd) - - openmc.deplete.comm.barrier() - if openmc.deplete.comm.rank == 0: - os.remove(os.path.join(cls.results, "results.h5")) - os.rmdir(cls.results) - - -if __name__ == '__main__': - unittest.main() + assert y1[2] == approx(s2[0]) + assert y2[2] == approx(s2[1]) diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 6166f15612..064b878afe 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -1,8 +1,7 @@ -"""Tests for depletion chains""" +"""Tests for openmc.deplete.Chain class.""" -from collections import OrderedDict +from collections.abc import Mapping import os -import unittest from pathlib import Path import numpy as np @@ -12,190 +11,184 @@ from openmc.deplete import comm, Chain, reaction_rates, nuclide _test_filename = str(Path(__file__).parents[2] / 'chains' / 'chain_test.xml') -class TestChain(unittest.TestCase): - """ Tests for Chain class.""" +def test_init(): + """Test depletion chain initialization.""" + dep = Chain() - def test__init__(self): - """ Test depletion chain initialization.""" - dep = Chain() - - self.assertIsInstance(dep.nuclides, list) - self.assertIsInstance(dep.nuclide_dict, OrderedDict) - self.assertIsInstance(dep.react_to_ind, OrderedDict) - - def test_n_nuclides(self): - """ Test depletion chain n_nuclides parameter. """ - dep = Chain() - - dep.nuclides = ["NucA", "NucB", "NucC"] - - self.assertEqual(dep.n_nuclides, 3) - - def test_from_endf(self): - """Test depletion chain building from ENDF. Empty at the moment until we figure - out a good way to unit-test this.""" - pass - - def test_from_xml(self): - """ Read chain_test.xml and ensure all values are correct. """ - # Unfortunately, this routine touches a lot of the code, but most of - # the components external to depletion_chain.py are simple storage - # types. - - dep = Chain.from_xml(_test_filename) - - # Basic checks - self.assertEqual(dep.n_nuclides, 3) - - # A tests - nuc = dep.nuclides[dep.nuclide_dict["A"]] - - self.assertEqual(nuc.name, "A") - self.assertEqual(nuc.half_life, 2.36520E+04) - self.assertEqual(nuc.n_decay_modes, 2) - modes = nuc.decay_modes - self.assertEqual([m.target for m in modes], ["B", "C"]) - self.assertEqual([m.type for m in modes], ["beta1", "beta2"]) - self.assertEqual([m.branching_ratio for m in modes], [0.6, 0.4]) - self.assertEqual(nuc.n_reaction_paths, 1) - self.assertEqual([r.target for r in nuc.reactions], ["C"]) - self.assertEqual([r.type for r in nuc.reactions], ["(n,gamma)"]) - self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0]) - - # B tests - nuc = dep.nuclides[dep.nuclide_dict["B"]] - - self.assertEqual(nuc.name, "B") - self.assertEqual(nuc.half_life, 3.29040E+04) - self.assertEqual(nuc.n_decay_modes, 1) - modes = nuc.decay_modes - self.assertEqual([m.target for m in modes], ["A"]) - self.assertEqual([m.type for m in modes], ["beta"]) - self.assertEqual([m.branching_ratio for m in modes], [1.0]) - self.assertEqual(nuc.n_reaction_paths, 1) - self.assertEqual([r.target for r in nuc.reactions], ["C"]) - self.assertEqual([r.type for r in nuc.reactions], ["(n,gamma)"]) - self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0]) - - # C tests - nuc = dep.nuclides[dep.nuclide_dict["C"]] - - self.assertEqual(nuc.name, "C") - self.assertEqual(nuc.n_decay_modes, 0) - self.assertEqual(nuc.n_reaction_paths, 3) - self.assertEqual([r.target for r in nuc.reactions], [None, "A", "B"]) - self.assertEqual([r.type for r in nuc.reactions], ["fission", "(n,gamma)", "(n,gamma)"]) - self.assertEqual([r.branching_ratio for r in nuc.reactions], [1.0, 0.7, 0.3]) - - # Yield tests - self.assertEqual(nuc.yield_energies, [0.0253]) - self.assertEqual(list(nuc.yield_data.keys()), [0.0253]) - self.assertEqual(nuc.yield_data[0.0253], - [("A", 0.0292737), ("B", 0.002566345)]) - - def test_export_to_xml(self): - """Test writing a depletion chain to XML.""" - - # Prevent different MPI ranks from conflicting - filename = 'test{}.xml'.format(comm.rank) - - A = nuclide.Nuclide() - A.name = "A" - A.half_life = 2.36520e4 - A.decay_modes = [ - nuclide.DecayTuple("beta1", "B", 0.6), - nuclide.DecayTuple("beta2", "C", 0.4) - ] - A.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] - - B = nuclide.Nuclide() - B.name = "B" - B.half_life = 3.29040e4 - B.decay_modes = [nuclide.DecayTuple("beta", "A", 1.0)] - B.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] - - C = nuclide.Nuclide() - C.name = "C" - C.reactions = [ - nuclide.ReactionTuple("fission", None, 2.0e8, 1.0), - nuclide.ReactionTuple("(n,gamma)", "A", 0.0, 0.7), - nuclide.ReactionTuple("(n,gamma)", "B", 0.0, 0.3) - ] - C.yield_energies = [0.0253] - C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} - - chain = Chain() - chain.nuclides = [A, B, C] - chain.export_to_xml(filename) - - original = open(_test_filename, 'r').read() - chain_xml = open(filename, 'r').read() - self.assertEqual(original, chain_xml) - - os.remove(filename) - - def test_form_matrix(self): - """ Using chain_test, and a dummy reaction rate, compute the matrix. """ - # Relies on test_from_xml passing. - - dep = Chain.from_xml(_test_filename) - - cell_ind = {"10000": 0, "10001": 1} - nuc_ind = {"A": 0, "B": 1, "C": 2} - react_ind = dep.react_to_ind - - react = reaction_rates.ReactionRates(cell_ind, nuc_ind, react_ind) - - dep.nuc_to_react_ind = nuc_ind - - react["10000", "C", "fission"] = 1.0 - react["10000", "A", "(n,gamma)"] = 2.0 - react["10000", "B", "(n,gamma)"] = 3.0 - react["10000", "C", "(n,gamma)"] = 4.0 - - mat = dep.form_matrix(react[0, :, :]) - # Loss A, decay, (n, gamma) - mat00 = -np.log(2) / 2.36520E+04 - 2 - # A -> B, decay, 0.6 branching ratio - mat10 = np.log(2) / 2.36520E+04 * 0.6 - # A -> C, decay, 0.4 branching ratio + (n,gamma) - mat20 = np.log(2) / 2.36520E+04 * 0.4 + 2 - - # B -> A, decay, 1.0 branching ratio - mat01 = np.log(2)/3.29040E+04 - # Loss B, decay, (n, gamma) - mat11 = -np.log(2)/3.29040E+04 - 3 - # B -> C, (n, gamma) - mat21 = 3 - - # C -> A fission, (n, gamma) - mat02 = 0.0292737 * 1.0 + 4.0 * 0.7 - # C -> B fission, (n, gamma) - mat12 = 0.002566345 * 1.0 + 4.0 * 0.3 - # Loss C, fission, (n, gamma) - mat22 = -1.0 - 4.0 - - self.assertEqual(mat[0, 0], mat00) - self.assertEqual(mat[1, 0], mat10) - self.assertEqual(mat[2, 0], mat20) - self.assertEqual(mat[0, 1], mat01) - self.assertEqual(mat[1, 1], mat11) - self.assertEqual(mat[2, 1], mat21) - self.assertEqual(mat[0, 2], mat02) - self.assertEqual(mat[1, 2], mat12) - self.assertEqual(mat[2, 2], mat22) - - def test_nuc_by_ind(self): - """ Test nuc_by_ind converter function. """ - dep = Chain() - - dep.nuclides = ["NucA", "NucB", "NucC"] - dep.nuclide_dict = {"NucA" : 0, "NucB" : 1, "NucC" : 2} - - self.assertEqual("NucA", dep.nuc_by_ind("NucA")) - self.assertEqual("NucB", dep.nuc_by_ind("NucB")) - self.assertEqual("NucC", dep.nuc_by_ind("NucC")) + assert isinstance(dep.nuclides, list) + assert isinstance(dep.nuclide_dict, Mapping) + assert isinstance(dep.react_to_ind, Mapping) -if __name__ == '__main__': - unittest.main() +def test_n_nuclides(): + """Test depletion chain n_nuclides parameter.""" + dep = Chain() + dep.nuclides = ["NucA", "NucB", "NucC"] + + assert dep.n_nuclides == 3 + + +def test_from_endf(): + """Test depletion chain building from ENDF. Empty at the moment until we figure + out a good way to unit-test this.""" + pass + + +def test_from_xml(): + """Read chain_test.xml and ensure all values are correct.""" + # Unfortunately, this routine touches a lot of the code, but most of + # the components external to depletion_chain.py are simple storage + # types. + + dep = Chain.from_xml(_test_filename) + + # Basic checks + assert dep.n_nuclides == 3 + + # A tests + nuc = dep.nuclides[dep.nuclide_dict["A"]] + + assert nuc.name == "A" + assert nuc.half_life == 2.36520E+04 + assert nuc.n_decay_modes == 2 + modes = nuc.decay_modes + assert [m.target for m in modes] == ["B", "C"] + assert [m.type for m in modes] == ["beta1", "beta2"] + assert [m.branching_ratio for m in modes] == [0.6, 0.4] + assert nuc.n_reaction_paths == 1 + assert [r.target for r in nuc.reactions] == ["C"] + assert [r.type for r in nuc.reactions] == ["(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0] + + # B tests + nuc = dep.nuclides[dep.nuclide_dict["B"]] + + assert nuc.name == "B" + assert nuc.half_life == 3.29040E+04 + assert nuc.n_decay_modes == 1 + modes = nuc.decay_modes + assert [m.target for m in modes] == ["A"] + assert [m.type for m in modes] == ["beta"] + assert [m.branching_ratio for m in modes] == [1.0] + assert nuc.n_reaction_paths == 1 + assert [r.target for r in nuc.reactions] == ["C"] + assert [r.type for r in nuc.reactions] == ["(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0] + + # C tests + nuc = dep.nuclides[dep.nuclide_dict["C"]] + + assert nuc.name == "C" + assert nuc.n_decay_modes == 0 + assert nuc.n_reaction_paths == 3 + assert [r.target for r in nuc.reactions] == [None, "A", "B"] + assert [r.type for r in nuc.reactions] == ["fission", "(n,gamma)", "(n,gamma)"] + assert [r.branching_ratio for r in nuc.reactions] == [1.0, 0.7, 0.3] + + # Yield tests + assert nuc.yield_energies == [0.0253] + assert list(nuc.yield_data) == [0.0253] + assert nuc.yield_data[0.0253] == [("A", 0.0292737), ("B", 0.002566345)] + + +def test_export_to_xml(run_in_tmpdir): + """Test writing a depletion chain to XML.""" + + # Prevent different MPI ranks from conflicting + filename = 'test{}.xml'.format(comm.rank) + + A = nuclide.Nuclide() + A.name = "A" + A.half_life = 2.36520e4 + A.decay_modes = [ + nuclide.DecayTuple("beta1", "B", 0.6), + nuclide.DecayTuple("beta2", "C", 0.4) + ] + A.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + B = nuclide.Nuclide() + B.name = "B" + B.half_life = 3.29040e4 + B.decay_modes = [nuclide.DecayTuple("beta", "A", 1.0)] + B.reactions = [nuclide.ReactionTuple("(n,gamma)", "C", 0.0, 1.0)] + + C = nuclide.Nuclide() + C.name = "C" + C.reactions = [ + nuclide.ReactionTuple("fission", None, 2.0e8, 1.0), + nuclide.ReactionTuple("(n,gamma)", "A", 0.0, 0.7), + nuclide.ReactionTuple("(n,gamma)", "B", 0.0, 0.3) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + + chain = Chain() + chain.nuclides = [A, B, C] + chain.export_to_xml(filename) + + original = open(_test_filename, 'r').read() + chain_xml = open(filename, 'r').read() + assert original == chain_xml + + +def test_form_matrix(): + """ Using chain_test, and a dummy reaction rate, compute the matrix. """ + # Relies on test_from_xml passing. + + dep = Chain.from_xml(_test_filename) + + cell_ind = {"10000": 0, "10001": 1} + nuc_ind = {"A": 0, "B": 1, "C": 2} + react_ind = dep.react_to_ind + + react = reaction_rates.ReactionRates(cell_ind, nuc_ind, react_ind) + + dep.nuc_to_react_ind = nuc_ind + + react["10000", "C", "fission"] = 1.0 + react["10000", "A", "(n,gamma)"] = 2.0 + react["10000", "B", "(n,gamma)"] = 3.0 + react["10000", "C", "(n,gamma)"] = 4.0 + + mat = dep.form_matrix(react[0, :, :]) + # Loss A, decay, (n, gamma) + mat00 = -np.log(2) / 2.36520E+04 - 2 + # A -> B, decay, 0.6 branching ratio + mat10 = np.log(2) / 2.36520E+04 * 0.6 + # A -> C, decay, 0.4 branching ratio + (n,gamma) + mat20 = np.log(2) / 2.36520E+04 * 0.4 + 2 + + # B -> A, decay, 1.0 branching ratio + mat01 = np.log(2)/3.29040E+04 + # Loss B, decay, (n, gamma) + mat11 = -np.log(2)/3.29040E+04 - 3 + # B -> C, (n, gamma) + mat21 = 3 + + # C -> A fission, (n, gamma) + mat02 = 0.0292737 * 1.0 + 4.0 * 0.7 + # C -> B fission, (n, gamma) + mat12 = 0.002566345 * 1.0 + 4.0 * 0.3 + # Loss C, fission, (n, gamma) + mat22 = -1.0 - 4.0 + + assert mat[0, 0] == mat00 + assert mat[1, 0] == mat10 + assert mat[2, 0] == mat20 + assert mat[0, 1] == mat01 + assert mat[1, 1] == mat11 + assert mat[2, 1] == mat21 + assert mat[0, 2] == mat02 + assert mat[1, 2] == mat12 + assert mat[2, 2] == mat22 + + +def test_nuc_by_ind(): + """ Test nuc_by_ind converter function. """ + dep = Chain() + dep.nuclides = ["NucA", "NucB", "NucC"] + dep.nuclide_dict = {"NucA" : 0, "NucB" : 1, "NucC" : 2} + + assert "NucA" == dep.nuc_by_ind("NucA") + assert "NucB" == dep.nuc_by_ind("NucB") + assert "NucC" == dep.nuc_by_ind("NucC") diff --git a/tests/unit_tests/test_deplete_cram.py b/tests/unit_tests/test_deplete_cram.py index 10f41fe2b6..21b93d17e3 100644 --- a/tests/unit_tests/test_deplete_cram.py +++ b/tests/unit_tests/test_deplete_cram.py @@ -1,48 +1,37 @@ -""" Tests for cram.py """ +""" Tests for cram.py -import unittest +Compares a few Mathematica matrix exponentials to CRAM16/CRAM48. +""" +from pytest import approx import numpy as np import scipy.sparse as sp from openmc.deplete.integrator import CRAM16, CRAM48 -class TestCram(unittest.TestCase): - """ Tests for cram.py +def test_CRAM16(): + """Test 16-term CRAM.""" + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 - Compares a few Mathematica matrix exponentials to CRAM16/CRAM48. - """ + z = CRAM16(mat, x, dt) - def test_CRAM16(self): - """ Test 16-term CRAM. """ - x = np.array([1.0, 1.0]) - mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) - dt = 0.1 + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) - z = CRAM16(mat, x, dt) - - # Solution from mathematica - z0 = np.array((0.904837418035960, 0.576799023327476)) - - tol = 1.0e-15 - - self.assertLess(np.linalg.norm(z - z0), tol) - - def test_CRAM48(self): - """ Test 48-term CRAM. """ - x = np.array([1.0, 1.0]) - mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) - dt = 0.1 - - z = CRAM48(mat, x, dt) - - # Solution from mathematica - z0 = np.array((0.904837418035960, 0.576799023327476)) - - tol = 1.0e-15 - - self.assertLess(np.linalg.norm(z - z0), tol) + assert z == approx(z0) -if __name__ == '__main__': - unittest.main() +def test_CRAM48(): + """Test 48-term CRAM.""" + x = np.array([1.0, 1.0]) + mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]]) + dt = 0.1 + + z = CRAM48(mat, x, dt) + + # Solution from mathematica + z0 = np.array((0.904837418035960, 0.576799023327476)) + + assert z == approx(z0) diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index 9b4cbe7802..3b6eed42dc 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -1,115 +1,101 @@ -""" Tests for integrator.py """ +"""Tests for integrator.py + +It is worth noting that openmc.deplete.integrate is extremely complex, to the +point I am unsure if it can be reasonably unit-tested. For the time being, it +will be left unimplemented and testing will be done via regression. + +""" import copy import os -import unittest from unittest.mock import MagicMock import numpy as np from openmc.deplete import integrator, ReactionRates, results, comm -class TestIntegrator(unittest.TestCase): - """ Tests for integrator.py +def test_save_results(run_in_tmpdir): + """Test data save module""" - It is worth noting that opendeplete.integrate is extremely complex, to - the point I am unsure if it can be reasonably unit-tested. For the time - being, it will be left unimplemented and testing will be done via - regression (in test_integrator_regression.py) - """ + stages = 3 - def test_save_results(self): - """ Test data save module """ + np.random.seed(comm.rank) - stages = 3 + # Mock geometry + op = MagicMock() - np.random.seed(comm.rank) + vol_dict = {} + full_burn_dict = {} - # Mock geometry - op = MagicMock() + j = 0 + for i in range(comm.size): + vol_dict[str(2*i)] = 1.2 + vol_dict[str(2*i + 1)] = 1.2 + full_burn_dict[str(2*i)] = j + full_burn_dict[str(2*i + 1)] = j + 1 + j += 2 - vol_dict = {} - full_burn_dict = {} + burn_list = [str(i) for i in range(2*comm.rank, 2*comm.rank + 2)] + nuc_list = ["na", "nb"] - j = 0 - for i in range(comm.size): - vol_dict[str(2*i)] = 1.2 - vol_dict[str(2*i + 1)] = 1.2 - full_burn_dict[str(2*i)] = j - full_burn_dict[str(2*i + 1)] = j + 1 - j += 2 + op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_dict - burn_list = [str(i) for i in range(2*comm.rank, 2*comm.rank + 2)] - nuc_list = ["na", "nb"] + # Construct x + x1 = [] + x2 = [] - op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_dict + for i in range(stages): + x1.append([np.random.rand(2), np.random.rand(2)]) + x2.append([np.random.rand(2), np.random.rand(2)]) - # Construct x - x1 = [] - x2 = [] + # Construct r + cell_dict = {s:i for i, s in enumerate(burn_list)} + r1 = ReactionRates(cell_dict, {"na":0, "nb":1}, {"ra":0, "rb":1}) + r1.rates = np.random.rand(2, 2, 2) - for i in range(stages): - x1.append([np.random.rand(2), np.random.rand(2)]) - x2.append([np.random.rand(2), np.random.rand(2)]) + rate1 = [] + rate2 = [] - # Construct r - cell_dict = {s:i for i, s in enumerate(burn_list)} - r1 = ReactionRates(cell_dict, {"na":0, "nb":1}, {"ra":0, "rb":1}) + for i in range(stages): + rate1.append(copy.deepcopy(r1)) + r1.rates = np.random.rand(2, 2, 2) + rate2.append(copy.deepcopy(r1)) r1.rates = np.random.rand(2, 2, 2) - rate1 = [] - rate2 = [] + # Create global terms + eigvl1 = np.random.rand(stages) + eigvl2 = np.random.rand(stages) + seed1 = [np.random.randint(100) for i in range(stages)] + seed2 = [np.random.randint(100) for i in range(stages)] - for i in range(stages): - rate1.append(copy.deepcopy(r1)) - r1.rates = np.random.rand(2, 2, 2) - rate2.append(copy.deepcopy(r1)) - r1.rates = np.random.rand(2, 2, 2) + eigvl1 = comm.bcast(eigvl1, root=0) + eigvl2 = comm.bcast(eigvl2, root=0) + seed1 = comm.bcast(seed1, root=0) + seed2 = comm.bcast(seed2, root=0) - # Create global terms - eigvl1 = np.random.rand(stages) - eigvl2 = np.random.rand(stages) - seed1 = [np.random.randint(100) for i in range(stages)] - seed2 = [np.random.randint(100) for i in range(stages)] + t1 = [0.0, 1.0] + t2 = [1.0, 2.0] - eigvl1 = comm.bcast(eigvl1, root=0) - eigvl2 = comm.bcast(eigvl2, root=0) - seed1 = comm.bcast(seed1, root=0) - seed2 = comm.bcast(seed2, root=0) + integrator.save_results(op, x1, rate1, eigvl1, seed1, t1, 0) + integrator.save_results(op, x2, rate2, eigvl2, seed2, t2, 1) - t1 = [0.0, 1.0] - t2 = [1.0, 2.0] + # Load the files + res = results.read_results("results.h5") - integrator.save_results(op, x1, rate1, eigvl1, seed1, t1, 0) - integrator.save_results(op, x2, rate2, eigvl2, seed2, t2, 1) + for i in range(stages): + for mat_i, mat in enumerate(burn_list): + for nuc_i, nuc in enumerate(nuc_list): + assert res[0][i, mat, nuc] == x1[i][mat_i][nuc_i] + assert res[1][i, mat, nuc] == x2[i][mat_i][nuc_i] + np.testing.assert_array_equal(res[0].rates[i][mat, nuc, :], + rate1[i][mat, nuc, :]) + np.testing.assert_array_equal(res[1].rates[i][mat, nuc, :], + rate2[i][mat, nuc, :]) - # Load the files - res = results.read_results("results.h5") + np.testing.assert_array_equal(res[0].k, eigvl1) + np.testing.assert_array_equal(res[0].seeds, seed1) + np.testing.assert_array_equal(res[0].time, t1) - for i in range(stages): - for mat_i, mat in enumerate(burn_list): - - for nuc_i, nuc in enumerate(nuc_list): - self.assertEqual(res[0][i, mat, nuc], x1[i][mat_i][nuc_i]) - self.assertEqual(res[1][i, mat, nuc], x2[i][mat_i][nuc_i]) - np.testing.assert_array_equal(res[0].rates[i][mat, nuc, :], - rate1[i][mat, nuc, :]) - np.testing.assert_array_equal(res[1].rates[i][mat, nuc, :], - rate2[i][mat, nuc, :]) - - np.testing.assert_array_equal(res[0].k, eigvl1) - np.testing.assert_array_equal(res[0].seeds, seed1) - np.testing.assert_array_equal(res[0].time, t1) - - np.testing.assert_array_equal(res[1].k, eigvl2) - np.testing.assert_array_equal(res[1].seeds, seed2) - np.testing.assert_array_equal(res[1].time, t2) - - # Delete files - comm.barrier() - if comm.rank == 0: - os.remove("results.h5") - - -if __name__ == '__main__': - unittest.main() + np.testing.assert_array_equal(res[1].k, eigvl2) + np.testing.assert_array_equal(res[1].seeds, seed2) + np.testing.assert_array_equal(res[1].time, t2) diff --git a/tests/unit_tests/test_deplete_nuclide.py b/tests/unit_tests/test_deplete_nuclide.py index ebcabc5ca9..2add13f866 100644 --- a/tests/unit_tests/test_deplete_nuclide.py +++ b/tests/unit_tests/test_deplete_nuclide.py @@ -1,44 +1,42 @@ -""" Tests for nuclide.py. """ +"""Tests for the openmc.deplete.Nuclide class.""" -import unittest import xml.etree.ElementTree as ET from openmc.deplete import nuclide -class TestNuclide(unittest.TestCase): - """ Tests for the nuclide class. """ +def test_n_decay_modes(): + """ Test the decay mode count parameter. """ - def test_n_decay_modes(self): - """ Test the decay mode count parameter. """ + nuc = nuclide.Nuclide() - nuc = nuclide.Nuclide() + nuc.decay_modes = [ + nuclide.DecayTuple("beta1", "a", 0.5), + nuclide.DecayTuple("beta2", "b", 0.3), + nuclide.DecayTuple("beta3", "c", 0.2) + ] - nuc.decay_modes = [ - nuclide.DecayTuple("beta1", "a", 0.5), - nuclide.DecayTuple("beta2", "b", 0.3), - nuclide.DecayTuple("beta3", "c", 0.2) - ] + assert nuc.n_decay_modes == 3 - self.assertEqual(nuc.n_decay_modes, 3) - def test_n_reaction_paths(self): - """ Test the reaction path count parameter. """ +def test_n_reaction_paths(): + """ Test the reaction path count parameter. """ - nuc = nuclide.Nuclide() + nuc = nuclide.Nuclide() - nuc.reactions = [ - nuclide.ReactionTuple("(n,2n)", "a", 0.0, 1.0), - nuclide.ReactionTuple("(n,3n)", "b", 0.0, 1.0), - nuclide.ReactionTuple("(n,4n)", "c", 0.0, 1.0) - ] + nuc.reactions = [ + nuclide.ReactionTuple("(n,2n)", "a", 0.0, 1.0), + nuclide.ReactionTuple("(n,3n)", "b", 0.0, 1.0), + nuclide.ReactionTuple("(n,4n)", "c", 0.0, 1.0) + ] - self.assertEqual(nuc.n_reaction_paths, 3) + assert nuc.n_reaction_paths == 3 - def test_from_xml(self): - """Test reading nuclide data from an XML element.""" - data = """ +def test_from_xml(): + """Test reading nuclide data from an XML element.""" + + data = """ @@ -55,67 +53,64 @@ class TestNuclide(unittest.TestCase): - """ + """ - element = ET.fromstring(data) - u235 = nuclide.Nuclide.from_xml(element) + element = ET.fromstring(data) + u235 = nuclide.Nuclide.from_xml(element) - self.assertEqual(u235.decay_modes, [ - nuclide.DecayTuple('sf', 'U235', 7.2e-11), - nuclide.DecayTuple('alpha', 'Th231', 1 - 7.2e-11) - ]) - self.assertEqual(u235.reactions, [ - nuclide.ReactionTuple('(n,2n)', 'U234', -5297781.0, 1.0), - nuclide.ReactionTuple('(n,3n)', 'U233', -12142300.0, 1.0), - nuclide.ReactionTuple('(n,4n)', 'U232', -17885600.0, 1.0), - nuclide.ReactionTuple('(n,gamma)', 'U236', 6545200.0, 1.0), - nuclide.ReactionTuple('fission', None, 193405400.0, 1.0), - ]) - self.assertEqual(u235.yield_energies, [0.0253]) - self.assertEqual(u235.yield_data, { - 0.0253: [('Te134', 0.062155), ('Zr100', 0.0497641), - ('Xe138', 0.0481413)] - }) - - def test_to_xml_element(self): - """Test writing nuclide data to an XML element.""" - - C = nuclide.Nuclide() - C.name = "C" - C.half_life = 0.123 - C.decay_modes = [ - nuclide.DecayTuple('beta-', 'B', 0.99), - nuclide.DecayTuple('alpha', 'D', 0.01) - ] - C.reactions = [ - nuclide.ReactionTuple('fission', None, 2.0e8, 1.0), - nuclide.ReactionTuple('(n,gamma)', 'A', 0.0, 1.0) - ] - C.yield_energies = [0.0253] - C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} - element = C.to_xml_element() - - self.assertEqual(element.get("half_life"), "0.123") - - decay_elems = element.findall("decay_type") - self.assertEqual(len(decay_elems), 2) - self.assertEqual(decay_elems[0].get("type"), "beta-") - self.assertEqual(decay_elems[0].get("target"), "B") - self.assertEqual(decay_elems[0].get("branching_ratio"), "0.99") - self.assertEqual(decay_elems[1].get("type"), "alpha") - self.assertEqual(decay_elems[1].get("target"), "D") - self.assertEqual(decay_elems[1].get("branching_ratio"), "0.01") - - rx_elems = element.findall("reaction_type") - self.assertEqual(len(rx_elems), 2) - self.assertEqual(rx_elems[0].get("type"), "fission") - self.assertEqual(float(rx_elems[0].get("Q")), 2.0e8) - self.assertEqual(rx_elems[1].get("type"), "(n,gamma)") - self.assertEqual(rx_elems[1].get("target"), "A") - self.assertEqual(float(rx_elems[1].get("Q")), 0.0) - - self.assertIsNotNone(element.find('neutron_fission_yields')) + assert u235.decay_modes == [ + nuclide.DecayTuple('sf', 'U235', 7.2e-11), + nuclide.DecayTuple('alpha', 'Th231', 1 - 7.2e-11) + ] + assert u235.reactions == [ + nuclide.ReactionTuple('(n,2n)', 'U234', -5297781.0, 1.0), + nuclide.ReactionTuple('(n,3n)', 'U233', -12142300.0, 1.0), + nuclide.ReactionTuple('(n,4n)', 'U232', -17885600.0, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'U236', 6545200.0, 1.0), + nuclide.ReactionTuple('fission', None, 193405400.0, 1.0), + ] + assert u235.yield_energies == [0.0253] + assert u235.yield_data == { + 0.0253: [('Te134', 0.062155), ('Zr100', 0.0497641), + ('Xe138', 0.0481413)] + } -if __name__ == '__main__': - unittest.main() +def test_to_xml_element(): + """Test writing nuclide data to an XML element.""" + + C = nuclide.Nuclide() + C.name = "C" + C.half_life = 0.123 + C.decay_modes = [ + nuclide.DecayTuple('beta-', 'B', 0.99), + nuclide.DecayTuple('alpha', 'D', 0.01) + ] + C.reactions = [ + nuclide.ReactionTuple('fission', None, 2.0e8, 1.0), + nuclide.ReactionTuple('(n,gamma)', 'A', 0.0, 1.0) + ] + C.yield_energies = [0.0253] + C.yield_data = {0.0253: [("A", 0.0292737), ("B", 0.002566345)]} + element = C.to_xml_element() + + assert element.get("half_life") == "0.123" + + decay_elems = element.findall("decay_type") + assert len(decay_elems) == 2 + assert decay_elems[0].get("type") == "beta-" + assert decay_elems[0].get("target") == "B" + assert decay_elems[0].get("branching_ratio") == "0.99" + assert decay_elems[1].get("type") == "alpha" + assert decay_elems[1].get("target") == "D" + assert decay_elems[1].get("branching_ratio") == "0.01" + + rx_elems = element.findall("reaction_type") + assert len(rx_elems) == 2 + assert rx_elems[0].get("type") == "fission" + assert float(rx_elems[0].get("Q")) == 2.0e8 + assert rx_elems[1].get("type") == "(n,gamma)" + assert rx_elems[1].get("target") == "A" + assert float(rx_elems[1].get("Q")) == 0.0 + + assert element.find('neutron_fission_yields') is not None diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index 6ad2007d9c..d4b2efd330 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -1,68 +1,40 @@ -""" Regression tests for predictor.py""" +"""Regression tests for openmc.deplete.integrator.predictor algorithm. -import os -import unittest +These tests integrate a simple test problem described in dummy_geometry.py. +""" -import numpy as np +from pytest import approx import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities from tests import dummy_geometry -class TestPredictorRegression(unittest.TestCase): - """ Regression tests for opendeplete.integrator.predictor algorithm. - These tests integrate a simple test problem described in dummy_geometry.py. - """ +def test_predictor(): + """Integral regression test of integrator algorithm using predictor/corrector""" - @classmethod - def setUpClass(cls): - """ Save current directory in case integrator crashes.""" - cls.cwd = os.getcwd() - cls.results = "test_integrator_regression" + settings = openmc.deplete.Settings() + settings.dt_vec = [0.75, 0.75] + settings.output_dir = "test_integrator_regression" - def test_predictor(self): - """ Integral regression test of integrator algorithm using CE/CM. """ + op = dummy_geometry.DummyGeometry(settings) - settings = openmc.deplete.Settings() - settings.dt_vec = [0.75, 0.75] - settings.output_dir = self.results + # Perform simulation using the predictor algorithm + openmc.deplete.predictor(op, print_out=False) - op = dummy_geometry.DummyGeometry(settings) + # Load the files + res = results.read_results(settings.output_dir + "/results.h5") - # Perform simulation using the predictor algorithm - openmc.deplete.predictor(op, print_out=False) + _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") + _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") - # Load the files - res = results.read_results(settings.output_dir + "/results.h5") + # Mathematica solution + s1 = [2.46847546272295, 0.986431226850467] + s2 = [4.11525874568034, -0.0581692232513460] - _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") - _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") + assert y1[1] == approx(s1[0]) + assert y2[1] == approx(s1[1]) - # Mathematica solution - s1 = [2.46847546272295, 0.986431226850467] - s2 = [4.11525874568034, -0.0581692232513460] - - tol = 1.0e-13 - - self.assertLess(np.absolute(y1[1] - s1[0]), tol) - self.assertLess(np.absolute(y2[1] - s1[1]), tol) - - self.assertLess(np.absolute(y1[2] - s2[0]), tol) - self.assertLess(np.absolute(y2[2] - s2[1]), tol) - - @classmethod - def tearDownClass(cls): - """ Clean up files""" - - os.chdir(cls.cwd) - - openmc.deplete.comm.barrier() - if openmc.deplete.comm.rank == 0: - os.remove(os.path.join(cls.results, "results.h5")) - os.rmdir(cls.results) - - -if __name__ == '__main__': - unittest.main() + assert y1[2] == approx(s2[0]) + assert y2[2] == approx(s2[1]) diff --git a/tests/unit_tests/test_deplete_reaction.py b/tests/unit_tests/test_deplete_reaction.py index 2139be16c2..a98535e1d8 100644 --- a/tests/unit_tests/test_deplete_reaction.py +++ b/tests/unit_tests/test_deplete_reaction.py @@ -1,86 +1,80 @@ -""" Tests for reaction_rates.py. """ - -import unittest +"""Tests for the openmc.deplete.ReactionRates class.""" from openmc.deplete import reaction_rates -class TestReactionRates(unittest.TestCase): - """ Tests for the ReactionRates class. """ +def test_indexing(): + """Tests the __getitem__ and __setitem__ routines simultaneously.""" - def test_indexing(self): - """Tests the __getitem__ and __setitem__ routines simultaneously.""" + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1} - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1} + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates["10000", "U238", "fission"] = 1.0 + rates["10001", "U238", "fission"] = 2.0 + rates["10000", "U235", "fission"] = 3.0 + rates["10001", "U235", "fission"] = 4.0 + rates["10000", "U238", "(n,gamma)"] = 5.0 + rates["10001", "U238", "(n,gamma)"] = 6.0 + rates["10000", "U235", "(n,gamma)"] = 7.0 + rates["10001", "U235", "(n,gamma)"] = 8.0 - rates["10000", "U238", "fission"] = 1.0 - rates["10001", "U238", "fission"] = 2.0 - rates["10000", "U235", "fission"] = 3.0 - rates["10001", "U235", "fission"] = 4.0 - rates["10000", "U238", "(n,gamma)"] = 5.0 - rates["10001", "U238", "(n,gamma)"] = 6.0 - rates["10000", "U235", "(n,gamma)"] = 7.0 - rates["10001", "U235", "(n,gamma)"] = 8.0 + # String indexing + assert rates["10000", "U238", "fission"] == 1.0 + assert rates["10001", "U238", "fission"] == 2.0 + assert rates["10000", "U235", "fission"] == 3.0 + assert rates["10001", "U235", "fission"] == 4.0 + assert rates["10000", "U238", "(n,gamma)"] == 5.0 + assert rates["10001", "U238", "(n,gamma)"] == 6.0 + assert rates["10000", "U235", "(n,gamma)"] == 7.0 + assert rates["10001", "U235", "(n,gamma)"] == 8.0 - # String indexing - self.assertEqual(rates["10000", "U238", "fission"], 1.0) - self.assertEqual(rates["10001", "U238", "fission"], 2.0) - self.assertEqual(rates["10000", "U235", "fission"], 3.0) - self.assertEqual(rates["10001", "U235", "fission"], 4.0) - self.assertEqual(rates["10000", "U238", "(n,gamma)"], 5.0) - self.assertEqual(rates["10001", "U238", "(n,gamma)"], 6.0) - self.assertEqual(rates["10000", "U235", "(n,gamma)"], 7.0) - self.assertEqual(rates["10001", "U235", "(n,gamma)"], 8.0) + # Int indexing + assert rates[0, 0, 0] == 1.0 + assert rates[1, 0, 0] == 2.0 + assert rates[0, 1, 0] == 3.0 + assert rates[1, 1, 0] == 4.0 + assert rates[0, 0, 1] == 5.0 + assert rates[1, 0, 1] == 6.0 + assert rates[0, 1, 1] == 7.0 + assert rates[1, 1, 1] == 8.0 - # Int indexing - self.assertEqual(rates[0, 0, 0], 1.0) - self.assertEqual(rates[1, 0, 0], 2.0) - self.assertEqual(rates[0, 1, 0], 3.0) - self.assertEqual(rates[1, 1, 0], 4.0) - self.assertEqual(rates[0, 0, 1], 5.0) - self.assertEqual(rates[1, 0, 1], 6.0) - self.assertEqual(rates[0, 1, 1], 7.0) - self.assertEqual(rates[1, 1, 1], 8.0) + rates[0, 0, 0] = 5.0 - rates[0, 0, 0] = 5.0 - - self.assertEqual(rates[0, 0, 0], 5.0) - self.assertEqual(rates["10000", "U238", "fission"], 5.0) - - def test_n_mat(self): - """ Test number of materials property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - - self.assertEqual(rates.n_mat, 2) - - def test_n_nuc(self): - """ Test number of nuclides property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - - self.assertEqual(rates.n_nuc, 3) - - def test_n_react(self): - """ Test number of reactions property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - - self.assertEqual(rates.n_react, 4) + assert rates[0, 0, 0] == 5.0 + assert rates["10000", "U238", "fission"] == 5.0 -if __name__ == '__main__': - unittest.main() +def test_n_mat(): + """Test number of materials property.""" + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + assert rates.n_mat == 2 + + +def test_n_nuc(): + """Test number of nuclides property.""" + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + assert rates.n_nuc == 3 + + +def test_n_react(): + """ Test number of reactions property. """ + mat_to_ind = {"10000" : 0, "10001" : 1} + nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} + react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + + rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + + assert rates.n_react == 4 From 939d47cffa59fd8570a60fbb255cb4a4a8164dff Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 12:46:23 -0600 Subject: [PATCH 114/212] Simplify OpenMCSettings class (can properly delegate to openmc.Settings) --- openmc/deplete/openmc_wrapper.py | 116 ++++++-------------- scripts/example_run.py | 18 +-- tests/regression_tests/test_deplete_full.py | 29 +++-- 3 files changed, 56 insertions(+), 107 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 5c7a1aebaa..bf0a124710 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -31,7 +31,7 @@ from .function import Settings, Operator -def chunks(items, n): +def _chunks(items, n): min_size, extra = divmod(len(items), n) j = 0 chunk_list = [] @@ -43,70 +43,61 @@ def chunks(items, n): class OpenMCSettings(Settings): - """The OpenMCSettings class. - - Extends Settings to provide information OpenMC needs to run. + """Extends Settings to provide information OpenMC needs to run. Attributes ---------- dt_vec : numpy.array - Array of time steps to take. (From Settings) - tol : float - Tolerance for adaptive time stepping. (From Settings) + Array of time steps to in units of [s] output_dir : str - Path to output directory to save results. (From Settings) + Path to output directory to save results. chain_file : str - Path to the depletion chain xml file. Defaults to the environment - variable "OPENDEPLETE_CHAIN" if it exists. - particles : int - Number of particles to simulate per batch. - batches : int - Number of batches. - inactive : int - Number of inactive batches. - lower_left : list of float - Coordinate of lower left of bounding box of geometry. - upper_right : list of float - Coordinate of upper right of bounding box of geometry. - entropy_dimension : list of int - Grid size of entropy. - dilute_initial : float, default 1.0e3 + Path to the depletion chain xml file. Defaults to the + :envvar:`OPENDEPLETE_CHAIN` environment variable if it exists. + dilute_initial : float Initial atom density to add for nuclides that are zero in initial condition to ensure they exist in the decay chain. Only done for - nuclides with reaction rates. + nuclides with reaction rates. Defaults to 1.0e3. round_number : bool Whether or not to round output to OpenMC to 8 digits. Useful in testing, as OpenMC is incredibly sensitive to exact values. - constant_seed : int - If present, all runs will be performed with this seed. power : float - Power of the reactor in W. For a 2D problem, the power can be given in + Power of the reactor in [W]. For a 2D problem, the power can be given in W/cm as long as the "volume" assigned to a depletion material is actually an area in cm^2. + settings : openmc.Settings + Settings for OpenMC simulations + """ + _depletion_attrs = {'dt_vec', 'output_dir', 'chain_file', 'dilute_initial', + 'round_number', 'power'} + def __init__(self): super().__init__() - # OpenMC specific try: self.chain_file = os.environ["OPENDEPLETE_CHAIN"] except KeyError: self.chain_file = None - self.particles = None - self.batches = None - self.inactive = None - self.lower_left = None - self.upper_right = None - self.entropy_dimension = None self.dilute_initial = 1.0e3 - - # OpenMC testing specific self.round_number = False - self.constant_seed = None - - # Depletion problem specific self.power = None + # Avoid setattr to create OpenMC settings + self.__dict__['settings'] = openmc.Settings() + + def __setattr__(self, name, value): + if name in self._depletion_attrs: + self.__dict__[name] = value + else: + setattr(self.__dict__['settings'], name, value) + + def __getattr__(self, name): + if name in self._depletion_attrs: + return self.__dict__[name] + else: + return getattr(self.__dict__['settings'], name) + class Materials(object): """The Materials class. @@ -290,8 +281,8 @@ class OpenMCOperator(Operator): i += 1 # Decompose geometry - mat_burn_lists = chunks(mat_burn, comm.size) - mat_not_burn_lists = chunks(mat_not_burn, comm.size) + mat_burn_lists = _chunks(mat_burn, comm.size) + mat_not_burn_lists = _chunks(mat_not_burn, comm.size) mat_tally_ind = OrderedDict() @@ -456,7 +447,7 @@ class OpenMCOperator(Operator): # Create XML files if comm.rank == 0: self.geometry.export_to_xml() - self.generate_settings_xml() + self.settings.settings.export_to_xml() self.generate_materials_xml() # Initialize OpenMC library @@ -526,46 +517,6 @@ class OpenMCOperator(Operator): materials.export_to_xml() - def generate_settings_xml(self): - """Generates settings.xml. - - This function creates settings.xml using the value of the settings - variable. - - Todo - ---- - Rewrite to generalize source box. - """ - - batches = self.settings.batches - inactive = self.settings.inactive - particles = self.settings.particles - - # Just a generic settings file to get it running. - settings_file = openmc.Settings() - settings_file.batches = batches - settings_file.inactive = inactive - settings_file.particles = particles - settings_file.source = openmc.Source(space=openmc.stats.Box( - self.settings.lower_left, self.settings.upper_right)) - - if self.settings.entropy_dimension is not None: - entropy_mesh = openmc.Mesh() - entropy_mesh.lower_left = self.settings.lower_left - entropy_mesh.upper_right = self.settings.upper_right - entropy_mesh.dimension = self.settings.entropy_dimension - settings_file.entropy_mesh = entropy_mesh - - # Set seed - if self.settings.constant_seed is not None: - seed = self.settings.constant_seed - else: - seed = random.randint(1, sys.maxsize-1) - - settings_file.seed = self.seed = seed - - settings_file.export_to_xml() - def _get_tally_nuclides(self): nuc_set = set() @@ -581,7 +532,6 @@ class OpenMCOperator(Operator): for i in range(1, comm.size): nuc_newset = comm.recv(source=i, tag=i) nuc_set |= nuc_newset - else: comm.send(nuc_set, dest=0, tag=comm.rank) diff --git a/scripts/example_run.py b/scripts/example_run.py index 78d7dceddc..56d42b21a7 100644 --- a/scripts/example_run.py +++ b/scripts/example_run.py @@ -1,6 +1,8 @@ """An example file showing how to run a simulation.""" import numpy as np +import openmc +from openmc.data import JOULE_PER_EV import openmc.deplete import example_geometry @@ -15,20 +17,18 @@ N = np.floor(dt2/dt1) dt = np.repeat([dt1], N) -# Create settings variable +# Depletion settings settings = openmc.deplete.OpenMCSettings() +settings.power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO +settings.dt_vec = dt +settings.output_dir = 'test' +# OpenMC-delegated settings settings.particles = 1000 settings.batches = 100 settings.inactive = 40 -settings.lower_left = lower_left -settings.upper_right = upper_right -settings.entropy_dimension = [10, 10, 1] - -joule_per_mev = 1.6021766208e-13 -settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO -settings.dt_vec = dt -settings.output_dir = 'test' +settings.source = openmc.Source(space=openmc.stats.Box(lower_left, upper_right)) +settings.verbosity = 3 op = openmc.deplete.OpenMCOperator(geometry, settings) diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 5f4af7a737..fcaa60eee5 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -5,6 +5,8 @@ import shutil from pathlib import Path import numpy as np +import openmc +from openmc.data import JOULE_PER_EV import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities @@ -35,26 +37,23 @@ def test_full(run_in_tmpdir): N = floor(dt2/dt1) dt = np.full(N, dt1) - # Create settings variable + # Depletion settings settings = openmc.deplete.OpenMCSettings() + settings.chain_file = str(Path(__file__).parents[2] / 'chains' / + 'chain_simple.xml') + settings.power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO + settings.dt_vec = dt + settings.output_dir = "test_full" + settings.round_number = True - - chain_file = str(Path(__file__).parents[2] / 'chains' / 'chain_simple.xml') - settings.chain_file = chain_file + # Add OpenMC-specific settings settings.particles = 100 settings.batches = 100 settings.inactive = 40 - settings.lower_left = lower_left - settings.upper_right = upper_right - settings.entropy_dimension = [10, 10, 1] - - settings.round_number = True - settings.constant_seed = 1 - - joule_per_mev = 1.6021766208e-13 - settings.power = 2.337e15*4*joule_per_mev # MeV/second cm from CASMO - settings.dt_vec = dt - settings.output_dir = "test_full" + space = openmc.stats.Box(lower_left, upper_right) + settings.source = openmc.Source(space=space) + settings.seed = 1 + settings.verbosity = 3 op = openmc.deplete.OpenMCOperator(geometry, settings) From f494fecf21b7e8de0066c27acdd1258e06641694 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 12:57:56 -0600 Subject: [PATCH 115/212] Change Operator.eval() -> Operator.__call__() --- openmc/deplete/function.py | 35 +++---- openmc/deplete/integrator/cecm.py | 6 +- openmc/deplete/integrator/predictor.py | 4 +- openmc/deplete/openmc_wrapper.py | 104 ++++++++++----------- tests/dummy_geometry.py | 16 ++-- tests/unit_tests/test_deplete_predictor.py | 2 +- 6 files changed, 84 insertions(+), 83 deletions(-) diff --git a/openmc/deplete/function.py b/openmc/deplete/function.py index bcc055e67b..b9694d88b1 100644 --- a/openmc/deplete/function.py +++ b/openmc/deplete/function.py @@ -27,33 +27,19 @@ class Settings(object): class Operator(metaclass=ABCMeta): - """The Operator metaclass. - - This defines all functions that the integrator needs to operate. + """Abstract class defining all methods needed for the integrator. Attributes ---------- settings : Settings Settings object. - """ + """ def __init__(self, settings): self.settings = settings @abstractmethod - def initial_condition(self): - """Performs final setup and returns initial condition. - - Returns - ------- - list of numpy.array - Total density for initial conditions. - """ - - pass - - @abstractmethod - def eval(self, vec, print_out=True): + def __call__(self, vec, print_out=True): """Runs a simulation. Parameters @@ -72,6 +58,17 @@ class Operator(metaclass=ABCMeta): seed : int Seed for this simulation. """ + pass + + @abstractmethod + def initial_condition(self): + """Performs final setup and returns initial condition. + + Returns + ------- + list of numpy.array + Total density for initial conditions. + """ pass @@ -114,3 +111,7 @@ class Operator(metaclass=ABCMeta): """ pass + + @abstractmethod + def finalize(self): + pass diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 699ccc2033..57a87c703e 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -62,7 +62,7 @@ def cecm(operator, print_out=True): eigvls = [] rates_array = [] - eigvl, rates, seed = operator.eval(x[0]) + eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) seeds.append(seed) @@ -86,7 +86,7 @@ def cecm(operator, print_out=True): x.append(x_result) - eigvl, rates, seed = operator.eval(x[1]) + eigvl, rates, seed = operator(x[1]) eigvls.append(eigvl) seeds.append(seed) @@ -119,7 +119,7 @@ def cecm(operator, print_out=True): seeds = [] eigvls = [] rates_array = [] - eigvl, rates, seed = operator.eval(x[0]) + eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) seeds.append(seed) diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 7b41e66493..1b8d00600c 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -53,7 +53,7 @@ def predictor(operator, print_out=True): eigvls = [] rates_array = [] - eigvl, rates, seed = operator.eval(x[0]) + eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) seeds.append(seed) @@ -86,7 +86,7 @@ def predictor(operator, print_out=True): seeds = [] eigvls = [] rates_array = [] - eigvl, rates, seed = operator.eval(x[0]) + eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) seeds.append(seed) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index bf0a124710..3dce9db7b9 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -207,6 +207,58 @@ class OpenMCOperator(Operator): # Create reaction rate tables self.initialize_reaction_rates() + def __call__(self, vec, print_out=True): + """Runs a simulation. + + Parameters + ---------- + vec : list of numpy.array + Total atoms to be used in function. + print_out : bool, optional + Whether or not to print out time. + + Returns + ------- + mat : list of scipy.sparse.csr_matrix + Matrices for the next step. + k : float + Eigenvalue of the problem. + rates : openmc.deplete.ReactionRates + Reaction rates from this simulation. + seed : int + Seed for this simulation. + """ + + # Prevent OpenMC from complaining about re-creating tallies + openmc.reset_auto_ids() + + # Update status + self.set_density(vec) + + time_start = time.time() + + # Update material compositions and tally nuclides + self._update_materials() + openmc.capi.tallies[1].nuclides = self._get_tally_nuclides() + + # Run OpenMC + openmc.capi.reset() + openmc.capi.run() + + time_openmc = time.time() + + # Extract results + k = self.unpack_tallies_and_normalize() + + if comm.rank == 0: + time_unpack = time.time() + + if print_out: + print("Time to openmc: ", time_openmc - time_start) + print("Time to unpack: ", time_unpack - time_openmc) + + return k, copy.deepcopy(self.reaction_rates), self.seed + def extract_mat_ids(self): """Extracts materials and assigns them to processes. @@ -365,58 +417,6 @@ class OpenMCOperator(Operator): self.chain.nuc_to_react_ind = self.burn_nuc_to_ind - def eval(self, vec, print_out=True): - """Runs a simulation. - - Parameters - ---------- - vec : list of numpy.array - Total atoms to be used in function. - print_out : bool, optional - Whether or not to print out time. - - Returns - ------- - mat : list of scipy.sparse.csr_matrix - Matrices for the next step. - k : float - Eigenvalue of the problem. - rates : openmc.deplete.ReactionRates - Reaction rates from this simulation. - seed : int - Seed for this simulation. - """ - - # Prevent OpenMC from complaining about re-creating tallies - openmc.reset_auto_ids() - - # Update status - self.set_density(vec) - - time_start = time.time() - - # Update material compositions and tally nuclides - self._update_materials() - openmc.capi.tallies[1].nuclides = self._get_tally_nuclides() - - # Run OpenMC - openmc.capi.reset() - openmc.capi.run() - - time_openmc = time.time() - - # Extract results - k = self.unpack_tallies_and_normalize() - - if comm.rank == 0: - time_unpack = time.time() - - if print_out: - print("Time to openmc: ", time_openmc - time_start) - print("Time to unpack: ", time_unpack - time_openmc) - - return k, copy.deepcopy(self.reaction_rates), self.seed - def form_matrix(self, y, mat): """Forms the depletion matrix. diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index ecdce567d6..585c1b11cd 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -21,14 +21,7 @@ class DummyGeometry(Operator): def __init__(self, settings): super().__init__(settings) - def finalize(self): - pass - - @property - def chain(self): - return self - - def eval(self, vec, print_out=False): + def __call__(self, vec, print_out=False): """Evaluates F(y) Parameters @@ -60,6 +53,13 @@ class DummyGeometry(Operator): # Create a fake rates object return 0.0, reaction_rates, 0 + def finalize(self): + pass + + @property + def chain(self): + return self + def form_matrix(self, rates): """Forms the f(y) matrix in y' = f(y)y. diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index d4b2efd330..d808c46b8e 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -11,7 +11,7 @@ from openmc.deplete import utilities from tests import dummy_geometry -def test_predictor(): +def test_predictor(run_in_tmpdir): """Integral regression test of integrator algorithm using predictor/corrector""" settings = openmc.deplete.Settings() From fc6b3bd9d9a36b23efced294eb32b0e9a30b9a76 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 13:39:40 -0600 Subject: [PATCH 116/212] Make Results.from_hdf5 a classmethod --- openmc/deplete/integrator/cecm.py | 2 +- openmc/deplete/results.py | 62 +++++++++++++------------------ 2 files changed, 27 insertions(+), 37 deletions(-) diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 57a87c703e..5432f172d0 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -30,7 +30,7 @@ def cecm(operator, print_out=True): .. [ref] Isotalo, Aarno. "Comparison of Neutronics-Depletion Coupling Schemes - for Burnup Calculations—Continued Study." Nuclear Science and + for Burnup Calculations-Continued Study." Nuclear Science and Engineering 180.3 (2015): 286-300. Parameters diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index c08b3ef40d..1a2ee4e437 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -302,7 +302,8 @@ class Results(object): if comm.rank == 0: time_dset[index, :] = self.time - def from_hdf5(self, handle, index): + @classmethod + def from_hdf5(cls, handle, index): """Loads results object from HDF5. Parameters @@ -312,6 +313,7 @@ class Results(object): index : int What step is this? """ + results = cls() # Grab handles number_dset = handle["/number"] @@ -319,15 +321,15 @@ class Results(object): seeds_dset = handle["/seeds"] time_dset = handle["/time"] - self.data = number_dset[index, :, :, :] - self.k = eigenvalues_dset[index, :] - self.seeds = seeds_dset[index, :] - self.time = time_dset[index, :] + results.data = number_dset[index, :, :, :] + results.k = eigenvalues_dset[index, :] + results.seeds = seeds_dset[index, :] + results.time = time_dset[index, :] # Reconstruct dictionaries - self.volume = OrderedDict() - self.mat_to_ind = OrderedDict() - self.nuc_to_ind = OrderedDict() + results.volume = OrderedDict() + results.mat_to_ind = OrderedDict() + results.nuc_to_ind = OrderedDict() rxn_nuc_to_ind = OrderedDict() rxn_to_ind = OrderedDict() @@ -336,13 +338,13 @@ class Results(object): vol = mat_handle.attrs["volume"] ind = mat_handle.attrs["index"] - self.volume[mat] = vol - self.mat_to_ind[mat] = ind + results.volume[mat] = vol + results.mat_to_ind[mat] = ind for nuc in handle["/nuclides"]: nuc_handle = handle["/nuclides/" + nuc] ind_atom = nuc_handle.attrs["atom number index"] - self.nuc_to_ind[nuc] = ind_atom + results.nuc_to_ind[nuc] = ind_atom if "reaction rate index" in nuc_handle.attrs: rxn_nuc_to_ind[nuc] = nuc_handle.attrs["reaction rate index"] @@ -351,13 +353,15 @@ class Results(object): rxn_handle = handle["/reactions/" + rxn] rxn_to_ind[rxn] = rxn_handle.attrs["index"] - self.rates = [] + results.rates = [] # Reconstruct reactions - for i in range(self.n_stages): - rate = ReactionRates(self.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) + for i in range(results.n_stages): + rate = ReactionRates(results.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) rate.rates = handle["/reaction rates"][index, i, :, :, :] - self.rates.append(rate) + results.rates.append(rate) + + return results def get_dict(number): @@ -419,7 +423,7 @@ def write_results(result, filename, index): def read_results(filename): - """Reads out a list of results objects from an hdf5 file. + """Return a list of Results objects from an HDF5 file. Parameters ---------- @@ -430,26 +434,12 @@ def read_results(filename): ------- results : list of Results The result objects. + """ + with h5py.File(filename, "r") as fh: + assert fh["version"].value == RESULTS_VERSION - file = h5py.File(filename, "r") + # Get number of results stored + n = fh["number"].value.shape[0] - assert file["/version"].value == RESULTS_VERSION - - # Grab handles - number_dset = file["/number"] - - # Get number of results stored - number_shape = list(number_dset.shape) - number_results = number_shape[0] - - results = [] - - for i in range(number_results): - result = Results() - result.from_hdf5(file, i) - results.append(result) - - file.close() - - return results + return [Results.from_hdf5(fh, i) for i in range(n)] From 730623246f53e25fd6875b04953ae3633aab4e75 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 14 Feb 2018 15:36:00 -0600 Subject: [PATCH 117/212] Rename results.h5 -> depletion_results.h5. Use /materials in HDF5 file --- openmc/deplete/integrator/save_results.py | 4 ++-- openmc/deplete/results.py | 12 ++++-------- scripts/example_plot.py | 2 +- scripts/example_run.py | 1 - tests/regression_tests/test_deplete_full.py | 2 +- tests/regression_tests/test_reference.h5 | Bin 165384 -> 231608 bytes tests/unit_tests/test_deplete_cecm.py | 2 +- tests/unit_tests/test_deplete_integrator.py | 2 +- tests/unit_tests/test_deplete_predictor.py | 2 +- 9 files changed, 11 insertions(+), 16 deletions(-) diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index 4f20b52fde..f580af838c 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -9,7 +9,7 @@ def save_results(op, x, rates, eigvls, seeds, t, step_ind): Parameters ---------- - op : Function + op : openmc.deplete.Operator The operator used to generate these results. x : list of list of numpy.array The prior x vectors. Indexed [i][cell] using the above equation. @@ -44,4 +44,4 @@ def save_results(op, x, rates, eigvls, seeds, t, step_ind): results.time = t results.rates = rates - write_results(results, "results.h5", step_ind) + write_results(results, "depletion_results.h5", step_ind) diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 1a2ee4e437..fd48bb4df1 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -52,7 +52,6 @@ class Results(object): self.k = None self.seeds = None self.time = None - self.p_terms = None self.rates = None self.volume = None @@ -192,7 +191,7 @@ class Results(object): n_rxn = len(rxn_list) n_stages = self.n_stages - mat_group = handle.create_group("cells") + mat_group = handle.create_group("materials") for mat in mat_list: mat_single_group = mat_group.create_group(mat) @@ -333,24 +332,21 @@ class Results(object): rxn_nuc_to_ind = OrderedDict() rxn_to_ind = OrderedDict() - for mat in handle["/cells"]: - mat_handle = handle["/cells/" + mat] + for mat, mat_handle in handle["/materials"].items(): vol = mat_handle.attrs["volume"] ind = mat_handle.attrs["index"] results.volume[mat] = vol results.mat_to_ind[mat] = ind - for nuc in handle["/nuclides"]: - nuc_handle = handle["/nuclides/" + nuc] + for nuc, nuc_handle in handle["/nuclides"].items(): ind_atom = nuc_handle.attrs["atom number index"] results.nuc_to_ind[nuc] = ind_atom if "reaction rate index" in nuc_handle.attrs: rxn_nuc_to_ind[nuc] = nuc_handle.attrs["reaction rate index"] - for rxn in handle["/reactions"]: - rxn_handle = handle["/reactions/" + rxn] + for rxn, rxn_handle in handle["/reactions"].items(): rxn_to_ind[rxn] = rxn_handle.attrs["index"] results.rates = [] diff --git a/scripts/example_plot.py b/scripts/example_plot.py index c92fef6bf2..ab5ac204d8 100644 --- a/scripts/example_plot.py +++ b/scripts/example_plot.py @@ -8,7 +8,7 @@ from openmc.deplete import (read_results, evaluate_single_nuclide, result_folder = "test" # Load data -results = read_results(result_folder + "/results.h5") +results = read_results(result_folder + "/deplete_results.h5") cell = "5" nuc = "Gd157" diff --git a/scripts/example_run.py b/scripts/example_run.py index 56d42b21a7..30b6bdc2ee 100644 --- a/scripts/example_run.py +++ b/scripts/example_run.py @@ -28,7 +28,6 @@ settings.particles = 1000 settings.batches = 100 settings.inactive = 40 settings.source = openmc.Source(space=openmc.stats.Box(lower_left, upper_right)) -settings.verbosity = 3 op = openmc.deplete.OpenMCOperator(geometry, settings) diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index fcaa60eee5..e775e7af86 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -61,7 +61,7 @@ def test_full(run_in_tmpdir): openmc.deplete.integrator.predictor(op) # Load the files - res_test = results.read_results(settings.output_dir + "/results.h5") + res_test = results.read_results(settings.output_dir + "/depletion_results.h5") # Load the reference filename = str(Path(__file__).with_name('test_reference.h5')) diff --git a/tests/regression_tests/test_reference.h5 b/tests/regression_tests/test_reference.h5 index ef3ae0090943bc7ecdc01a1afaa70c0216e029f0..f832e3e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+NddIdL0E{v*^9BN)%rmuN2jy1>v$DfO3&za}7TxnmN!=dtL^(qU? zQDqf4uCo2AQK?c1({eJQciFfFUABSaE|aermnxTVsJue2viEsZ83vB4Y+Ueu+ES!M z&D@NP8?e%qK;%n_Iy%ezoRl7ds}L8V^10(lO9QweR;8X4JvbNi>TZ%<7*!{GX`5{& z^<~d}5ldA9j+fne-K-#Pv@h5pjk>G!E^A*#mo3gc@ut~eDm=pZ@@l=s&R5YQst$8Vp!V(hnpbW^wGGbgf5)sHuCp)6;c$7qUgN|%)Y$t* zuzcl`(Wuf0(=oYG?=iFiJvzW$F&c+!#pZisaVtZwv!Ud>IK3!~~Z?_9R6&HA!8??khm zZ;G;yw}Jt)H|I+G5*?x_p4H2o+>A0Kz|C4R9>3bigz2e}XL<%(fLvWMSQOf$q zlU4?BLkwS;p1-j3RzK*K-6Xp(s!n!DBWH)c=-nKu4ebbyAO2Xt?2Ne2z9fPZ=6m%X zqxYc41m^~BG#XVJVLn!N>OH2viyrekgX06U&3uIA-8UcMhaK_5=+WDf+p>gV?S<#D96j zygfW-s*8Td~DAh#l)3SqRp9Yh-&m}};ai3nMG;hnh7Me?q$|Ib9^X000%N%)G Q!*hq`vcUB6KWAq7$Bg66+$yY`3sm<}8}c9W2{B cSQs0YbHWrkOgv~leZqD|r|n&980&5V0K4QAp8x;= diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 264ad21671..7fe8c6a043 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -24,7 +24,7 @@ def test_cecm(run_in_tmpdir): openmc.deplete.cecm(op, print_out=False) # Load the files - res = results.read_results(settings.output_dir + "/results.h5") + res = results.read_results(settings.output_dir + "/depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index 3b6eed42dc..964f99eee3 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -80,7 +80,7 @@ def test_save_results(run_in_tmpdir): integrator.save_results(op, x2, rate2, eigvl2, seed2, t2, 1) # Load the files - res = results.read_results("results.h5") + res = results.read_results("depletion_results.h5") for i in range(stages): for mat_i, mat in enumerate(burn_list): diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index d808c46b8e..8ec8964bbd 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -24,7 +24,7 @@ def test_predictor(run_in_tmpdir): openmc.deplete.predictor(op, print_out=False) # Load the files - res = results.read_results(settings.output_dir + "/results.h5") + res = results.read_results(settings.output_dir + "/depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") From b3106a65044a4978ad36fe75e9ca8ab0aae0092b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 06:37:46 -0600 Subject: [PATCH 118/212] Make Operator a context manager. Smart handling of output_dir --- openmc/deplete/__init__.py | 2 +- openmc/deplete/{function.py => abc.py} | 32 ++++- openmc/deplete/integrator/cecm.py | 142 +++++++++----------- openmc/deplete/integrator/predictor.py | 94 ++++++------- openmc/deplete/openmc_wrapper.py | 13 +- tests/dummy_geometry.py | 5 +- tests/regression_tests/test_deplete_full.py | 3 +- tests/unit_tests/test_deplete_cecm.py | 2 +- tests/unit_tests/test_deplete_predictor.py | 2 +- 9 files changed, 144 insertions(+), 151 deletions(-) rename openmc/deplete/{function.py => abc.py} (78%) diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py index 19d1d13201..2467b973a9 100644 --- a/openmc/deplete/__init__.py +++ b/openmc/deplete/__init__.py @@ -18,7 +18,7 @@ from .nuclide import * from .chain import * from .openmc_wrapper import * from .reaction_rates import * -from .function import * +from .abc import * from .results import * from .integrator import * from .utilities import * diff --git a/openmc/deplete/function.py b/openmc/deplete/abc.py similarity index 78% rename from openmc/deplete/function.py rename to openmc/deplete/abc.py index b9694d88b1..63a80b45c7 100644 --- a/openmc/deplete/function.py +++ b/openmc/deplete/abc.py @@ -4,6 +4,9 @@ This module contains the Operator class, which is then passed to an integrator to run a full depletion simulation. """ +import os +from pathlib import Path + from abc import ABCMeta, abstractmethod @@ -16,14 +19,22 @@ class Settings(object): ---------- dt_vec : numpy.array Array of time steps to take. - output_dir : str + output_dir : pathlib.Path Path to output directory to save results. - """ + """ def __init__(self): # Integrator specific self.dt_vec = None - self.output_dir = None + self.output_dir = Path('.') + + @property + def output_dir(self): + return self._output_dir + + @output_dir.setter + def output_dir(self, output_dir): + self._output_dir = Path(output_dir) class Operator(metaclass=ABCMeta): @@ -60,6 +71,20 @@ class Operator(metaclass=ABCMeta): """ pass + def __enter__(self): + # Save current directory and move to specific output directory + self._orig_dir = os.getcwd() + self.settings.output_dir.mkdir(exist_ok=True) + + # In Python 3.6+, chdir accepts a Path directly + os.chdir(str(self.settings.output_dir)) + + return self.initial_condition() + + def __exit__(self, exc_type, exc_value, traceback): + self.finalize() + os.chdir(self._orig_dir) + @abstractmethod def initial_condition(self): """Performs final setup and returns initial condition. @@ -112,6 +137,5 @@ class Operator(metaclass=ABCMeta): pass - @abstractmethod def finalize(self): pass diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 5432f172d0..148b02b4ad 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -41,96 +41,82 @@ def cecm(operator, print_out=True): Whether or not to print out time. """ - # Save current directory - dir_home = os.getcwd() - - # Move to folder - os.makedirs(operator.settings.output_dir, exist_ok=True) - os.chdir(operator.settings.output_dir) - # Generate initial conditions - vec = operator.initial_condition() + with operator as vec: + n_mats = len(vec) - n_mats = len(vec) + t = 0.0 - t = 0.0 + for i, dt in enumerate(operator.settings.dt_vec): + # Create vectors + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] - for i, dt in enumerate(operator.settings.dt_vec): - # Create vectors + eigvl, rates, seed = operator(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[0][i, :, :] for i in range(n_mats)) + dts = repeat(dt/2, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + x.append(x_result) + + eigvl, rates, seed = operator(x[1]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[1][i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + + t += dt + vec = copy.deepcopy(x_result) + + # Perform one last simulation x = [copy.deepcopy(vec)] seeds = [] eigvls = [] rates_array = [] - eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) seeds.append(seed) rates_array.append(rates) - t_start = time.time() - - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[0][i, :, :] for i in range(n_mats)) - dts = repeat(dt/2, n_mats) - - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) - - x.append(x_result) - - eigvl, rates, seed = operator(x[1]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) - - t_start = time.time() - - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[1][i, :, :] for i in range(n_mats)) - dts = repeat(dt, n_mats) - - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) - # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) - - t += dt - vec = copy.deepcopy(x_result) - - # Perform one last simulation - x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) - - # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t], - len(operator.settings.dt_vec)) - - # Return to origin - os.chdir(dir_home) - - # Release resources - operator.finalize() + save_results(operator, x, rates_array, eigvls, seeds, [t, t], + len(operator.settings.dt_vec)) diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 1b8d00600c..8d499d1ff4 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -32,27 +32,52 @@ def predictor(operator, print_out=True): Whether or not to print out time. """ - # Save current directory - dir_home = os.getcwd() - - # Move to folder - os.makedirs(operator.settings.output_dir, exist_ok=True) - os.chdir(operator.settings.output_dir) - # Generate initial conditions - vec = operator.initial_condition() + with operator as vec: + n_mats = len(vec) - n_mats = len(vec) + t = 0.0 - t = 0.0 + for i, dt in enumerate(operator.settings.dt_vec): + # Create vectors + x = [copy.deepcopy(vec)] + seeds = [] + eigvls = [] + rates_array = [] - for i, dt in enumerate(operator.settings.dt_vec): - # Create vectors + eigvl, rates, seed = operator(x[0]) + + eigvls.append(eigvl) + seeds.append(seed) + rates_array.append(rates) + + # Create results, write to disk + save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + + t_start = time.time() + + chains = repeat(operator.chain, n_mats) + vecs = (x[0][i] for i in range(n_mats)) + rates = (rates_array[0][i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + t += dt + vec = copy.deepcopy(x_result) + + # Perform one last simulation x = [copy.deepcopy(vec)] seeds = [] eigvls = [] rates_array = [] - eigvl, rates, seed = operator(x[0]) eigvls.append(eigvl) @@ -60,44 +85,5 @@ def predictor(operator, print_out=True): rates_array.append(rates) # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) - - t_start = time.time() - - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[0][i, :, :] for i in range(n_mats)) - dts = repeat(dt, n_mats) - - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) - - t += dt - vec = copy.deepcopy(x_result) - - # Perform one last simulation - x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) - - # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t], - len(operator.settings.dt_vec)) - - # Return to origin - os.chdir(dir_home) - - # Release resources - operator.finalize() + save_results(operator, x, rates_array, eigvls, seeds, [t, t], + len(operator.settings.dt_vec)) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 3dce9db7b9..701a35b7d3 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -23,12 +23,10 @@ import openmc import openmc.capi from openmc.data import JOULE_PER_EV from . import comm +from .abc import Settings, Operator from .atom_number import AtomNumber from .chain import Chain from .reaction_rates import ReactionRates -from .function import Settings, Operator - - def _chunks(items, n): @@ -49,7 +47,7 @@ class OpenMCSettings(Settings): ---------- dt_vec : numpy.array Array of time steps to in units of [s] - output_dir : str + output_dir : pathlib.Path Path to output directory to save results. chain_file : str Path to the depletion chain xml file. Defaults to the @@ -70,7 +68,7 @@ class OpenMCSettings(Settings): """ - _depletion_attrs = {'dt_vec', 'output_dir', 'chain_file', 'dilute_initial', + _depletion_attrs = {'dt_vec', '_output_dir', 'chain_file', 'dilute_initial', 'round_number', 'power'} def __init__(self): @@ -87,7 +85,10 @@ class OpenMCSettings(Settings): self.__dict__['settings'] = openmc.Settings() def __setattr__(self, name, value): - if name in self._depletion_attrs: + if hasattr(self.__class__, name): + prop = getattr(self.__class__, name) + prop.fset(self, value) + elif name in self._depletion_attrs: self.__dict__[name] = value else: setattr(self.__dict__['settings'], name, value) diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index 585c1b11cd..aab396b85a 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -1,7 +1,7 @@ import numpy as np import scipy.sparse as sp from openmc.deplete.reaction_rates import ReactionRates -from openmc.deplete.function import Operator +from openmc.deplete.abc import Operator class DummyGeometry(Operator): @@ -53,9 +53,6 @@ class DummyGeometry(Operator): # Create a fake rates object return 0.0, reaction_rates, 0 - def finalize(self): - pass - @property def chain(self): return self diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index e775e7af86..c809ba0536 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -43,7 +43,6 @@ def test_full(run_in_tmpdir): 'chain_simple.xml') settings.power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO settings.dt_vec = dt - settings.output_dir = "test_full" settings.round_number = True # Add OpenMC-specific settings @@ -61,7 +60,7 @@ def test_full(run_in_tmpdir): openmc.deplete.integrator.predictor(op) # Load the files - res_test = results.read_results(settings.output_dir + "/depletion_results.h5") + res_test = results.read_results(settings.output_dir / "depletion_results.h5") # Load the reference filename = str(Path(__file__).with_name('test_reference.h5')) diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 7fe8c6a043..66c3ee156c 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -24,7 +24,7 @@ def test_cecm(run_in_tmpdir): openmc.deplete.cecm(op, print_out=False) # Load the files - res = results.read_results(settings.output_dir + "/depletion_results.h5") + res = results.read_results(settings.output_dir / "depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index 8ec8964bbd..f1133f87d2 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -24,7 +24,7 @@ def test_predictor(run_in_tmpdir): openmc.deplete.predictor(op, print_out=False) # Load the files - res = results.read_results(settings.output_dir + "/depletion_results.h5") + res = results.read_results(settings.output_dir / "depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") From 484a0238888315242c5327d9a4ef7163ba806e64 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 07:03:01 -0600 Subject: [PATCH 119/212] Move more attributes to abc.Settings --- openmc/deplete/abc.py | 20 ++++++++++++++++++-- openmc/deplete/openmc_wrapper.py | 15 ++++++--------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 63a80b45c7..e2b286d6a4 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -21,12 +21,28 @@ class Settings(object): Array of time steps to take. output_dir : pathlib.Path Path to output directory to save results. + chain_file : str + Path to the depletion chain xml file. Defaults to the + :envvar:`OPENDEPLETE_CHAIN` environment variable if it exists. + dilute_initial : float + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. Defaults to 1.0e3. + power : float + Power of the reactor in [W]. For a 2D problem, the power can be given in + W/cm as long as the "volume" assigned to a depletion material is + actually an area in cm^2. """ def __init__(self): - # Integrator specific + try: + self.chain_file = os.environ["OPENDEPLETE_CHAIN"] + except KeyError: + self.chain_file = None self.dt_vec = None - self.output_dir = Path('.') + self.output_dir = '.' + self.power = None + self.dilute_initial = 1.0e3 @property def output_dir(self): diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 701a35b7d3..b5b91f2ac4 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -56,13 +56,13 @@ class OpenMCSettings(Settings): Initial atom density to add for nuclides that are zero in initial condition to ensure they exist in the decay chain. Only done for nuclides with reaction rates. Defaults to 1.0e3. - round_number : bool - Whether or not to round output to OpenMC to 8 digits. - Useful in testing, as OpenMC is incredibly sensitive to exact values. power : float Power of the reactor in [W]. For a 2D problem, the power can be given in W/cm as long as the "volume" assigned to a depletion material is actually an area in cm^2. + round_number : bool + Whether or not to round output to OpenMC to 8 digits. + Useful in testing, as OpenMC is incredibly sensitive to exact values. settings : openmc.Settings Settings for OpenMC simulations @@ -73,24 +73,21 @@ class OpenMCSettings(Settings): def __init__(self): super().__init__() - try: - self.chain_file = os.environ["OPENDEPLETE_CHAIN"] - except KeyError: - self.chain_file = None - self.dilute_initial = 1.0e3 self.round_number = False - self.power = None # Avoid setattr to create OpenMC settings self.__dict__['settings'] = openmc.Settings() def __setattr__(self, name, value): if hasattr(self.__class__, name): + # Use properties when appropriate prop = getattr(self.__class__, name) prop.fset(self, value) elif name in self._depletion_attrs: + # For known attributes, store in dictionary self.__dict__[name] = value else: + # otherwise, delegate to openmc.Settings setattr(self.__dict__['settings'], name, value) def __getattr__(self, name): From 998a562a33b214fa41f62166ebd78c83eb77aed8 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 09:47:37 -0600 Subject: [PATCH 120/212] Have Operator() return a namedtuple (simplifies integrators quite a bit) --- openmc/deplete/abc.py | 4 ++ openmc/deplete/integrator/cecm.py | 58 ++++++--------------- openmc/deplete/integrator/predictor.py | 42 +++++---------- openmc/deplete/integrator/save_results.py | 20 +++---- openmc/deplete/openmc_wrapper.py | 4 +- tests/dummy_geometry.py | 4 +- tests/unit_tests/test_deplete_integrator.py | 15 ++++-- 7 files changed, 55 insertions(+), 92 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index e2b286d6a4..155261742c 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -4,6 +4,7 @@ This module contains the Operator class, which is then passed to an integrator to run a full depletion simulation. """ +from collections import namedtuple import os from pathlib import Path @@ -53,6 +54,9 @@ class Settings(object): self._output_dir = Path(output_dir) +OperatorResult = namedtuple('OperatorResult', ['k', 'rates', 'seed']) + + class Operator(metaclass=ABCMeta): """Abstract class defining all methods needed for the integrator. diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 148b02b4ad..16fa299fd3 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -12,7 +12,7 @@ from .save_results import save_results def cecm(operator, print_out=True): - """The CE/CM integrator. + r"""The CE/CM integrator. Implements the second order CE/CM Predictor-Corrector algorithm [ref]_. This algorithm is mathematically defined as: @@ -22,11 +22,11 @@ def cecm(operator, print_out=True): A_p &= A(y_n, t_n) - y_m &= \\text{expm}(A_p h/2) y_n + y_m &= \text{expm}(A_p h/2) y_n A_c &= A(y_m, t_n + h/2) - y_{n+1} &= \\text{expm}(A_c h) y_n + y_{n+1} &= \text{expm}(A_c h) y_n .. [ref] Isotalo, Aarno. "Comparison of Neutronics-Depletion Coupling Schemes @@ -35,88 +35,64 @@ def cecm(operator, print_out=True): Parameters ---------- - operator : Operator + operator : openmc.deplete.Operator The operator object to simulate on. print_out : bool, optional Whether or not to print out time. - """ + """ # Generate initial conditions with operator as vec: n_mats = len(vec) t = 0.0 - for i, dt in enumerate(operator.settings.dt_vec): - # Create vectors + # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) + results = [operator(x[0])] + # Deplete for first half of timestep t_start = time.time() - chains = repeat(operator.chain, n_mats) vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[0][i, :, :] for i in range(n_mats)) + rates = (results[0].rates[i, :, :] for i in range(n_mats)) dts = repeat(dt/2, n_mats) - with Pool() as pool: iters = zip(chains, vecs, rates, dts) x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() if comm.rank == 0: if print_out: print("Time to matexp: ", t_end - t_start) + # Get middle-of-timestep reaction rates x.append(x_result) + results.append(operator(x_result)) - eigvl, rates, seed = operator(x[1]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) - + # Deplete for second half of timestep t_start = time.time() - chains = repeat(operator.chain, n_mats) vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[1][i, :, :] for i in range(n_mats)) + rates = (results[1].rates[i, :, :] for i in range(n_mats)) dts = repeat(dt, n_mats) - with Pool() as pool: iters = zip(chains, vecs, rates, dts) x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() if comm.rank == 0: if print_out: print("Time to matexp: ", t_end - t_start) # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + save_results(operator, x, results, [t, t + dt], i) + # Advance time, update vector t += dt vec = copy.deepcopy(x_result) # Perform one last simulation x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) + results = [operator(x[0])] # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t], - len(operator.settings.dt_vec)) + save_results(operator, x, results, [t, t], len(operator.settings.dt_vec)) diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 8d499d1ff4..872b5ebb19 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -12,7 +12,7 @@ from .save_results import save_results def predictor(operator, print_out=True): - """The basic predictor integrator. + r"""The basic predictor integrator. Implements the first order predictor algorithm. This algorithm is mathematically defined as: @@ -22,68 +22,50 @@ def predictor(operator, print_out=True): A_p &= A(y_n, t_n) - y_{n+1} &= \\text{expm}(A_p h) y_n + y_{n+1} &= \text{expm}(A_p h) y_n Parameters ---------- - operator : Operator + operator : openmc.deplete.Operator The operator object to simulate on. print_out : bool, optional Whether or not to print out time. - """ + """ # Generate initial conditions with operator as vec: n_mats = len(vec) t = 0.0 - for i, dt in enumerate(operator.settings.dt_vec): - # Create vectors + # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) + results = [operator(x[0])] # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t + dt], i) + save_results(operator, x, results, [t, t + dt], i) + # Deplete for full timestep t_start = time.time() - chains = repeat(operator.chain, n_mats) vecs = (x[0][i] for i in range(n_mats)) - rates = (rates_array[0][i, :, :] for i in range(n_mats)) + rates = (results[0].rates[i, :, :] for i in range(n_mats)) dts = repeat(dt, n_mats) - with Pool() as pool: iters = zip(chains, vecs, rates, dts) x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() if comm.rank == 0: if print_out: print("Time to matexp: ", t_end - t_start) + # Advance time, update vector t += dt vec = copy.deepcopy(x_result) # Perform one last simulation x = [copy.deepcopy(vec)] - seeds = [] - eigvls = [] - rates_array = [] - eigvl, rates, seed = operator(x[0]) - - eigvls.append(eigvl) - seeds.append(seed) - rates_array.append(rates) + results = [operator(x[0])] # Create results, write to disk - save_results(operator, x, rates_array, eigvls, seeds, [t, t], - len(operator.settings.dt_vec)) + save_results(operator, x, results, [t, t], len(operator.settings.dt_vec)) diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index f580af838c..31cd9b2880 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -4,8 +4,8 @@ from ..results import Results, write_results -def save_results(op, x, rates, eigvls, seeds, t, step_ind): - """ Creates and writes results to disk +def save_results(op, x, op_results, t, step_ind): + """Creates and writes depletion results to disk Parameters ---------- @@ -13,18 +13,14 @@ def save_results(op, x, rates, eigvls, seeds, t, step_ind): The operator used to generate these results. x : list of list of numpy.array The prior x vectors. Indexed [i][cell] using the above equation. - rates : list of ReactionRates - The reaction rates for each substep. - eigvls : list of float - Eigenvalue for each substep - seeds : list of int - Seeds for each substep. + op_results : list of openmc.deplete.OperatorResult + Results of applying transport operator t : list of float Time indices. step_ind : int Step index. - """ + """ # Get indexing terms vol_list, nuc_list, burn_list, full_burn_list = op.get_results_info() @@ -39,9 +35,9 @@ def save_results(op, x, rates, eigvls, seeds, t, step_ind): for mat_i in range(n_mat): results[i, mat_i, :] = x[i][mat_i][:] - results.k = eigvls - results.seeds = seeds + results.k = [r.k for r in op_results] + results.seeds = [r.seed for r in op_results] + results.rates = [r.rates for r in op_results] results.time = t - results.rates = rates write_results(results, "depletion_results.h5", step_ind) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index b5b91f2ac4..da397c0149 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -23,7 +23,7 @@ import openmc import openmc.capi from openmc.data import JOULE_PER_EV from . import comm -from .abc import Settings, Operator +from .abc import Settings, Operator, OperatorResult from .atom_number import AtomNumber from .chain import Chain from .reaction_rates import ReactionRates @@ -255,7 +255,7 @@ class OpenMCOperator(Operator): print("Time to openmc: ", time_openmc - time_start) print("Time to unpack: ", time_unpack - time_openmc) - return k, copy.deepcopy(self.reaction_rates), self.seed + return OperatorResult(k, copy.deepcopy(self.reaction_rates), self.seed) def extract_mat_ids(self): """Extracts materials and assigns them to processes. diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index aab396b85a..ceafc3fdc2 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -1,7 +1,7 @@ import numpy as np import scipy.sparse as sp from openmc.deplete.reaction_rates import ReactionRates -from openmc.deplete.abc import Operator +from openmc.deplete.abc import Operator, OperatorResult class DummyGeometry(Operator): @@ -51,7 +51,7 @@ class DummyGeometry(Operator): reaction_rates[0, 1, 0] = vec[0][1] # Create a fake rates object - return 0.0, reaction_rates, 0 + return OperatorResult(0.0, reaction_rates, 0) @property def chain(self): diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index 964f99eee3..faccd3392f 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -11,7 +11,8 @@ import os from unittest.mock import MagicMock import numpy as np -from openmc.deplete import integrator, ReactionRates, results, comm +from openmc.deplete import (integrator, ReactionRates, results, comm, + OperatorResult) def test_save_results(run_in_tmpdir): @@ -49,8 +50,8 @@ def test_save_results(run_in_tmpdir): x2.append([np.random.rand(2), np.random.rand(2)]) # Construct r - cell_dict = {s:i for i, s in enumerate(burn_list)} - r1 = ReactionRates(cell_dict, {"na":0, "nb":1}, {"ra":0, "rb":1}) + cell_dict = {s: i for i, s in enumerate(burn_list)} + r1 = ReactionRates(cell_dict, {"na": 0, "nb": 1}, {"ra": 0, "rb": 1}) r1.rates = np.random.rand(2, 2, 2) rate1 = [] @@ -76,8 +77,12 @@ def test_save_results(run_in_tmpdir): t1 = [0.0, 1.0] t2 = [1.0, 2.0] - integrator.save_results(op, x1, rate1, eigvl1, seed1, t1, 0) - integrator.save_results(op, x2, rate2, eigvl2, seed2, t2, 1) + op_result1 = [OperatorResult(k, rates, seed) + for k, rates, seed in zip(eigvl1, rate1, seed1)] + op_result2 = [OperatorResult(k, rates, seed) + for k, rates, seed in zip(eigvl2, rate2, seed2)] + integrator.save_results(op, x1, op_result1, t1, 0) + integrator.save_results(op, x2, op_result2, t2, 1) # Load the files res = results.read_results("depletion_results.h5") From b62e25bcf5f84e5178990519a5e6c2ec433cb7bd Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 10:39:16 -0600 Subject: [PATCH 121/212] Simplify integrator implementations by separating out function for depletion --- openmc/deplete/integrator/cecm.py | 46 +++++------------------- openmc/deplete/integrator/cram.py | 50 ++++++++++++++++++++++++++ openmc/deplete/integrator/predictor.py | 29 ++++----------- 3 files changed, 65 insertions(+), 60 deletions(-) diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 16fa299fd3..760e3c89d8 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -1,13 +1,8 @@ -""" The CE/CM integrator.""" +"""The CE/CM integrator.""" import copy -from itertools import repeat -import os -from multiprocessing import Pool -import time -from .. import comm -from .cram import CRAM48, cram_wrapper +from .cram import deplete from .save_results import save_results @@ -43,8 +38,7 @@ def cecm(operator, print_out=True): """ # Generate initial conditions with operator as vec: - n_mats = len(vec) - + chain = operator.chain t = 0.0 for i, dt in enumerate(operator.settings.dt_vec): # Get beginning-of-timestep reaction rates @@ -52,43 +46,21 @@ def cecm(operator, print_out=True): results = [operator(x[0])] # Deplete for first half of timestep - t_start = time.time() - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (results[0].rates[i, :, :] for i in range(n_mats)) - dts = repeat(dt/2, n_mats) - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) + x_middle = deplete(chain, x[0], results[0], dt/2, print_out) # Get middle-of-timestep reaction rates - x.append(x_result) - results.append(operator(x_result)) + x.append(x_middle) + results.append(operator(x_middle)) - # Deplete for second half of timestep - t_start = time.time() - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (results[1].rates[i, :, :] for i in range(n_mats)) - dts = repeat(dt, n_mats) - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) + # Deplete for full timestep using beginning-of-step materials + x_end = deplete(chain, x[0], results[1], dt, print_out) # Create results, write to disk save_results(operator, x, results, [t, t + dt], i) # Advance time, update vector t += dt - vec = copy.deepcopy(x_result) + vec = copy.deepcopy(x_end) # Perform one last simulation x = [copy.deepcopy(vec)] diff --git a/openmc/deplete/integrator/cram.py b/openmc/deplete/integrator/cram.py index 56476384c6..09207fbc6b 100644 --- a/openmc/deplete/integrator/cram.py +++ b/openmc/deplete/integrator/cram.py @@ -3,10 +3,60 @@ Implements two different forms of CRAM for use in openmc.deplete. """ +from itertools import repeat +from multiprocessing import Pool +import time + import numpy as np import scipy.sparse as sp import scipy.sparse.linalg as sla +from .. import comm + + +def deplete(chain, x, op_result, dt, print_out): + """Deplete materials using given reaction rates for a specified time + + Parameters + ---------- + chain : openmc.deplete.Chain + Depletion chain + x : list of numpy.ndarray + Atom number vectors for each material + op_result : openmc.deplete.OperatorResult + Result of applying transport operator (contains reaction rates) + dt : float + Time in [s] to deplete for + print_out : bool + Whether to show elapsed time + + Returns + ------- + x_result : list of numpy.ndarray + Updated atom number vectors for each material + + """ + t_start = time.time() + + # Set up iterators + n_mats = len(x) + chains = repeat(chain, n_mats) + vecs = (x[i] for i in range(n_mats)) + rates = (op_result.rates[i, :, :] for i in range(n_mats)) + dts = repeat(dt, n_mats) + + # Use multiprocessing pool to distribute work + with Pool() as pool: + iters = zip(chains, vecs, rates, dts) + x_result = list(pool.starmap(cram_wrapper, iters)) + + t_end = time.time() + if comm.rank == 0: + if print_out: + print("Time to matexp: ", t_end - t_start) + + return x_result + def cram_wrapper(chain, n0, rates, dt): """Wraps depletion matrix creation / CRAM solve for multiprocess execution diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 872b5ebb19..0640783318 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -1,20 +1,15 @@ -""" The Predictor algorithm.""" +"""The Predictor algorithm.""" import copy -from itertools import repeat -import os -from multiprocessing import Pool -import time -from .. import comm -from .cram import CRAM48, cram_wrapper +from .cram import deplete from .save_results import save_results def predictor(operator, print_out=True): r"""The basic predictor integrator. - Implements the first order predictor algorithm. This algorithm is + Implements the first-order predictor algorithm. This algorithm is mathematically defined as: .. math:: @@ -34,8 +29,7 @@ def predictor(operator, print_out=True): """ # Generate initial conditions with operator as vec: - n_mats = len(vec) - + chain = operator.chain t = 0.0 for i, dt in enumerate(operator.settings.dt_vec): # Get beginning-of-timestep reaction rates @@ -46,22 +40,11 @@ def predictor(operator, print_out=True): save_results(operator, x, results, [t, t + dt], i) # Deplete for full timestep - t_start = time.time() - chains = repeat(operator.chain, n_mats) - vecs = (x[0][i] for i in range(n_mats)) - rates = (results[0].rates[i, :, :] for i in range(n_mats)) - dts = repeat(dt, n_mats) - with Pool() as pool: - iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) - t_end = time.time() - if comm.rank == 0: - if print_out: - print("Time to matexp: ", t_end - t_start) + x_end = deplete(chain, x[0], results[0], dt, print_out) # Advance time, update vector t += dt - vec = copy.deepcopy(x_result) + vec = copy.deepcopy(x_end) # Perform one last simulation x = [copy.deepcopy(vec)] From bc4d631883032791249d8e63824a0fbe159d7af9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 11:02:48 -0600 Subject: [PATCH 122/212] Get rid of deplete.Materials class that wasn't used --- openmc/deplete/openmc_wrapper.py | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index da397c0149..4668249b1f 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -97,25 +97,6 @@ class OpenMCSettings(Settings): return getattr(self.__dict__['settings'], name) -class Materials(object): - """The Materials class. - - Contains information about cross sections for a cell. - - Attributes - ---------- - temperature : float - Temperature in Kelvin for each region. - sab : str or list of str - ENDF S(a,b) name for a region that needs S(a,b) data. Not set if no - S(a,b) needed for region. - """ - - def __init__(self): - self.temperature = None - self.sab = None - - class OpenMCOperator(Operator): """The OpenMC Operator class. @@ -134,8 +115,6 @@ class OpenMCOperator(Operator): Settings object. (From Operator) geometry : openmc.Geometry The OpenMC geometry object. - materials : list of Materials - Materials to be used for this simulation. seed : int The RNG seed used in last OpenMC run. number : openmc.deplete.AtomNumber From 8a41bac17abdb16868dcbb6a4666e80a3f9b493c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 14:31:03 -0600 Subject: [PATCH 123/212] Removing a few attributes on OpenMCOperator --- openmc/deplete/abc.py | 2 +- openmc/deplete/integrator/save_results.py | 1 - openmc/deplete/openmc_wrapper.py | 27 +++------------------ openmc/deplete/results.py | 15 +----------- tests/dummy_geometry.py | 2 +- tests/unit_tests/test_deplete_integrator.py | 12 ++------- 6 files changed, 9 insertions(+), 50 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 155261742c..23322d91ca 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -54,7 +54,7 @@ class Settings(object): self._output_dir = Path(output_dir) -OperatorResult = namedtuple('OperatorResult', ['k', 'rates', 'seed']) +OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) class Operator(metaclass=ABCMeta): diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index 31cd9b2880..8a0ae92040 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -36,7 +36,6 @@ def save_results(op, x, op_results, t, step_ind): results[i, mat_i, :] = x[i][mat_i][:] results.k = [r.k for r in op_results] - results.seeds = [r.seed for r in op_results] results.rates = [r.rates for r in op_results] results.time = t diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 4668249b1f..d9a5d405ad 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -115,8 +115,6 @@ class OpenMCOperator(Operator): Settings object. (From Operator) geometry : openmc.Geometry The OpenMC geometry object. - seed : int - The RNG seed used in last OpenMC run. number : openmc.deplete.AtomNumber Total number of atoms in simulation. participating_nuclides : set of str @@ -125,10 +123,6 @@ class OpenMCOperator(Operator): The depletion chain information necessary to form matrices and tallies. reaction_rates : openmc.deplete.ReactionRates Reaction rates from the last operator step. - power : OrderedDict of str to float - Material-by-Material power. Indexed by material ID. - mat_name : OrderedDict of str to int - The name of region each material is set to. Indexed by material ID. burn_mat_to_id : OrderedDict of str to int Dictionary mapping material ID (as a string) to an index in reaction_rates. burn_nuc_to_id : OrderedDict of str to int @@ -144,12 +138,9 @@ class OpenMCOperator(Operator): super().__init__(settings) self.geometry = geometry - self.seed = 0 self.number = None self.participating_nuclides = None self.reaction_rates = None - self.power = None - self.mat_name = OrderedDict() self.burn_mat_to_ind = OrderedDict() self.burn_nuc_to_ind = None @@ -196,16 +187,10 @@ class OpenMCOperator(Operator): Returns ------- - mat : list of scipy.sparse.csr_matrix - Matrices for the next step. - k : float - Eigenvalue of the problem. - rates : openmc.deplete.ReactionRates - Reaction rates from this simulation. - seed : int - Seed for this simulation. - """ + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator + """ # Prevent OpenMC from complaining about re-creating tallies openmc.reset_auto_ids() @@ -234,7 +219,7 @@ class OpenMCOperator(Operator): print("Time to openmc: ", time_openmc - time_start) print("Time to unpack: ", time_unpack - time_openmc) - return OperatorResult(k, copy.deepcopy(self.reaction_rates), self.seed) + return OperatorResult(k, copy.deepcopy(self.reaction_rates)) def extract_mat_ids(self): """Extracts materials and assigns them to processes. @@ -262,8 +247,6 @@ class OpenMCOperator(Operator): # Iterate once through the geometry to get dictionaries cells = self.geometry.get_all_material_cells() for cell in cells.values(): - name = cell.name - if isinstance(cell.fill, openmc.Material): mat = cell.fill for nuclide in mat.get_nuclide_densities(): @@ -273,7 +256,6 @@ class OpenMCOperator(Operator): volume[str(mat.id)] = mat.volume else: mat_not_burn.add(str(mat.id)) - self.mat_name[mat.id] = name else: for mat in cell.fill: for nuclide in mat.get_nuclide_densities(): @@ -283,7 +265,6 @@ class OpenMCOperator(Operator): volume[str(mat.id)] = mat.volume else: mat_not_burn.add(str(mat.id)) - self.mat_name[mat.id] = name need_vol = [] diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index fd48bb4df1..37c4b6e921 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -22,8 +22,6 @@ class Results(object): ---------- k : list of float Eigenvalue for each substep. - seeds : list of int - Seeds for each substep. time : list of float Time at beginning, end of step, in seconds. n_mat : int @@ -46,11 +44,10 @@ class Results(object): Number of stages in simulation. data : numpy.array Atom quantity, stored by stage, mat, then by nuclide. - """ + """ def __init__(self): self.k = None - self.seeds = None self.time = None self.rates = None self.volume = None @@ -227,8 +224,6 @@ class Results(object): handle.create_dataset("eigenvalues", (1, n_stages), maxshape=(None, n_stages), dtype='float64') - handle.create_dataset("seeds", (1, n_stages), maxshape=(None, n_stages), dtype='int64') - handle.create_dataset("time", (1, 2), maxshape=(None, 2), dtype='float64') def to_hdf5(self, handle, index): @@ -252,7 +247,6 @@ class Results(object): number_dset = handle["/number"] rxn_dset = handle["/reaction rates"] eigenvalues_dset = handle["/eigenvalues"] - seeds_dset = handle["/seeds"] time_dset = handle["/time"] # Get number of results stored @@ -274,10 +268,6 @@ class Results(object): eigenvalues_shape[0] = new_shape eigenvalues_dset.resize(eigenvalues_shape) - seeds_shape = list(seeds_dset.shape) - seeds_shape[0] = new_shape - seeds_dset.resize(seeds_shape) - time_shape = list(time_dset.shape) time_shape[0] = new_shape time_dset.resize(time_shape) @@ -297,7 +287,6 @@ class Results(object): rxn_dset[index, i, low:high+1, :, :] = self.rates[i][:, :, :] if comm.rank == 0: eigenvalues_dset[index, i] = self.k[i] - seeds_dset[index, i] = self.seeds[i] if comm.rank == 0: time_dset[index, :] = self.time @@ -317,12 +306,10 @@ class Results(object): # Grab handles number_dset = handle["/number"] eigenvalues_dset = handle["/eigenvalues"] - seeds_dset = handle["/seeds"] time_dset = handle["/time"] results.data = number_dset[index, :, :, :] results.k = eigenvalues_dset[index, :] - results.seeds = seeds_dset[index, :] results.time = time_dset[index, :] # Reconstruct dictionaries diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index ceafc3fdc2..c013bb0054 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -51,7 +51,7 @@ class DummyGeometry(Operator): reaction_rates[0, 1, 0] = vec[0][1] # Create a fake rates object - return OperatorResult(0.0, reaction_rates, 0) + return OperatorResult(0.0, reaction_rates) @property def chain(self): diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index faccd3392f..59d08b4842 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -66,21 +66,15 @@ def test_save_results(run_in_tmpdir): # Create global terms eigvl1 = np.random.rand(stages) eigvl2 = np.random.rand(stages) - seed1 = [np.random.randint(100) for i in range(stages)] - seed2 = [np.random.randint(100) for i in range(stages)] eigvl1 = comm.bcast(eigvl1, root=0) eigvl2 = comm.bcast(eigvl2, root=0) - seed1 = comm.bcast(seed1, root=0) - seed2 = comm.bcast(seed2, root=0) t1 = [0.0, 1.0] t2 = [1.0, 2.0] - op_result1 = [OperatorResult(k, rates, seed) - for k, rates, seed in zip(eigvl1, rate1, seed1)] - op_result2 = [OperatorResult(k, rates, seed) - for k, rates, seed in zip(eigvl2, rate2, seed2)] + op_result1 = [OperatorResult(k, rates) for k, rates in zip(eigvl1, rate1)] + op_result2 = [OperatorResult(k, rates) for k, rates in zip(eigvl2, rate2)] integrator.save_results(op, x1, op_result1, t1, 0) integrator.save_results(op, x2, op_result2, t2, 1) @@ -98,9 +92,7 @@ def test_save_results(run_in_tmpdir): rate2[i][mat, nuc, :]) np.testing.assert_array_equal(res[0].k, eigvl1) - np.testing.assert_array_equal(res[0].seeds, seed1) np.testing.assert_array_equal(res[0].time, t1) np.testing.assert_array_equal(res[1].k, eigvl2) - np.testing.assert_array_equal(res[1].seeds, seed2) np.testing.assert_array_equal(res[1].time, t2) From 3bbd1774537bd2cfd5c0d775caefd7cfdd0f290f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 14:53:11 -0600 Subject: [PATCH 124/212] Have unpack_tallies_and_normalize return an OperatorResult --- openmc/deplete/abc.py | 11 ++++------- openmc/deplete/openmc_wrapper.py | 28 +++++++++++----------------- openmc/deplete/reaction_rates.py | 2 +- 3 files changed, 16 insertions(+), 25 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 23322d91ca..b2594d2c84 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -58,7 +58,7 @@ OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) class Operator(metaclass=ABCMeta): - """Abstract class defining all methods needed for the integrator. + """Abstract class defining a transport operator Attributes ---------- @@ -82,12 +82,9 @@ class Operator(metaclass=ABCMeta): Returns ------- - k : float - Eigenvalue of the problem. - rates : ReactionRates - Reaction rates from this simulation. - seed : int - Seed for this simulation. + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator + """ pass diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index d9a5d405ad..65ed4793dd 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -98,9 +98,7 @@ class OpenMCSettings(Settings): class OpenMCOperator(Operator): - """The OpenMC Operator class. - - Provides Operator functions for OpenMC. + """OpenMC transport operator Parameters ---------- @@ -210,7 +208,7 @@ class OpenMCOperator(Operator): time_openmc = time.time() # Extract results - k = self.unpack_tallies_and_normalize() + op_result = self.unpack_tallies_and_normalize() if comm.rank == 0: time_unpack = time.time() @@ -219,7 +217,7 @@ class OpenMCOperator(Operator): print("Time to openmc: ", time_openmc - time_start) print("Time to unpack: ", time_unpack - time_openmc) - return OperatorResult(k, copy.deepcopy(self.reaction_rates)) + return copy.deepcopy(op_result) def extract_mat_ids(self): """Extracts materials and assigns them to processes. @@ -561,23 +559,19 @@ class OpenMCOperator(Operator): self.number.set_mat_slice(i, total_density[i]) def unpack_tallies_and_normalize(self): - """Unpack tallies from OpenMC + """Unpack tallies from OpenMC and return an operator result - This function reads the tallies generated by OpenMC (from the tally.xml - file generated in generate_tally_xml) normalizes them so that the total - power generated is new_power, and then stores them in the reaction rate - database. + This method uses OpenMC's C API bindings to determine the k-effective + value and reaction rates from the simulation. The reaction rates are + normalized by the user-specified power, summing the product of the + fission reaction rate times the fission Q value for each material. Returns ------- - k : float - Eigenvalue of the last simulation. + openmc.deplete.OperatorResult + Eigenvalue and reaction rates resulting from transport operator - Todo - ---- - Provide units for power """ - rates = self.reaction_rates rates[:, :, :] = 0.0 @@ -655,7 +649,7 @@ class OpenMCOperator(Operator): # Scale reaction rates to obtain units of reactions/sec rates[:, :, :] *= power / energy - return k_combined + return OperatorResult(k_combined, rates) def load_participating(self): """Loads a cross_sections.xml file to find participating nuclides. diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index de3a6a7280..e8bab101bf 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -23,7 +23,7 @@ class ReactionRates(object): Attributes ---------- mat_to_ind : OrderedDict of str to int - A dictionary mapping cell ID as string to index. + A dictionary mapping material ID as string to index. nuc_to_ind : OrderedDict of str to int A dictionary mapping nuclide name as string to index. react_to_ind : OrderedDict of str to int From 05afc55a88c11200d387519de6a71be9063dbbbc Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 15:34:00 -0600 Subject: [PATCH 125/212] Give deplete.Chain some special methods to make it more Pythonic --- openmc/deplete/chain.py | 34 +++++++++----------------- openmc/deplete/openmc_wrapper.py | 9 +++---- tests/unit_tests/test_deplete_chain.py | 25 ++++++++++--------- 3 files changed, 29 insertions(+), 39 deletions(-) diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 03decb72ab..846b3af564 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -113,8 +113,6 @@ class Chain(object): Attributes ---------- - n_nuclides : int - Number of nuclides in chain. nuclides : list of Nuclide List of nuclides in chain. nuclide_dict : OrderedDict of str to int @@ -132,8 +130,14 @@ class Chain(object): self.nuc_to_react_ind = OrderedDict() self.react_to_ind = OrderedDict() - @property - def n_nuclides(self): + def __contains__(self, nuclide): + return nuclide in self.nuclide_dict + + def __getitem__(self, name): + """Get a Nuclide by name.""" + return self.nuclides[self.nuclide_dict[name]] + + def __len__(self): """Number of nuclides in chain.""" return len(self.nuclides) @@ -381,14 +385,14 @@ class Chain(object): Parameters ---------- rates : numpy.ndarray - 2D array indexed by nuclide then by cell. + 2D array indexed by (nuclide, reaction) Returns ------- scipy.sparse.csr_matrix Sparse matrix representing depletion. - """ + """ matrix = defaultdict(float) reactions = set() @@ -450,21 +454,7 @@ class Chain(object): reactions.clear() # Use DOK matrix as intermediate representation, then convert to CSR and return - matrix_dok = sp.dok_matrix((self.n_nuclides, self.n_nuclides)) + n = len(self) + matrix_dok = sp.dok_matrix((n, n)) dict.update(matrix_dok, matrix) return matrix_dok.tocsr() - - def nuc_by_ind(self, ind): - """Extracts nuclides from the list by dictionary key. - - Parameters - ---------- - ind : str - Name of nuclide. - - Returns - ------- - Nuclide - Nuclide object that corresponds to ind. - """ - return self.nuclides[self.nuclide_dict[ind]] diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 65ed4793dd..b8b9065276 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -328,7 +328,7 @@ class OpenMCOperator(Operator): i += 1 n_mat_burn = len(mat_burn) - n_nuc_burn = len(self.chain.nuclide_dict) + n_nuc_burn = len(self.chain) self.number = AtomNumber(mat_dict, nuc_dict, volume, n_mat_burn, n_nuc_burn) @@ -500,8 +500,7 @@ class OpenMCOperator(Operator): # Store list of tally nuclides on each process nuc_list = comm.bcast(nuc_list, root=0) - tally_nuclides = [nuc for nuc in nuc_list - if nuc in self.chain.nuclide_dict] + tally_nuclides = [nuc for nuc in nuc_list if nuc in self.chain] return tally_nuclides @@ -690,14 +689,14 @@ class OpenMCOperator(Operator): # and nuclides in depletion chain. if name not in self.participating_nuclides: self.participating_nuclides.add(name) - if name in self.chain.nuclide_dict: + if name in self.chain: self.burn_nuc_to_ind[name] = nuc_ind nuc_ind += 1 @property def n_nuc(self): """Number of nuclides considered in the decay chain.""" - return len(self.chain.nuclides) + return len(self.chain) def get_results_info(self): """Returns volume list, cell lists, and nuc lists. diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 064b878afe..3a065fb46f 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -20,12 +20,12 @@ def test_init(): assert isinstance(dep.react_to_ind, Mapping) -def test_n_nuclides(): - """Test depletion chain n_nuclides parameter.""" +def test_len(): + """Test depletion chain length.""" dep = Chain() dep.nuclides = ["NucA", "NucB", "NucC"] - assert dep.n_nuclides == 3 + assert len(dep) == 3 def test_from_endf(): @@ -43,10 +43,10 @@ def test_from_xml(): dep = Chain.from_xml(_test_filename) # Basic checks - assert dep.n_nuclides == 3 + assert len(dep) == 3 # A tests - nuc = dep.nuclides[dep.nuclide_dict["A"]] + nuc = dep["A"] assert nuc.name == "A" assert nuc.half_life == 2.36520E+04 @@ -61,7 +61,7 @@ def test_from_xml(): assert [r.branching_ratio for r in nuc.reactions] == [1.0] # B tests - nuc = dep.nuclides[dep.nuclide_dict["B"]] + nuc = dep["B"] assert nuc.name == "B" assert nuc.half_life == 3.29040E+04 @@ -76,7 +76,7 @@ def test_from_xml(): assert [r.branching_ratio for r in nuc.reactions] == [1.0] # C tests - nuc = dep.nuclides[dep.nuclide_dict["C"]] + nuc = dep["C"] assert nuc.name == "C" assert nuc.n_decay_modes == 0 @@ -183,12 +183,13 @@ def test_form_matrix(): assert mat[2, 2] == mat22 -def test_nuc_by_ind(): +def test_getitem(): """ Test nuc_by_ind converter function. """ dep = Chain() dep.nuclides = ["NucA", "NucB", "NucC"] - dep.nuclide_dict = {"NucA" : 0, "NucB" : 1, "NucC" : 2} + dep.nuclide_dict = {nuc: dep.nuclides.index(nuc) + for nuc in dep.nuclides} - assert "NucA" == dep.nuc_by_ind("NucA") - assert "NucB" == dep.nuc_by_ind("NucB") - assert "NucC" == dep.nuc_by_ind("NucC") + assert "NucA" == dep["NucA"] + assert "NucB" == dep["NucB"] + assert "NucC" == dep["NucC"] From a6c095c4e9dd480b382d48ce0d3301648f8942b5 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Feb 2018 15:37:41 -0600 Subject: [PATCH 126/212] Bugfix for Python 3.4 --- openmc/deplete/abc.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index b2594d2c84..5441829b40 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -91,7 +91,8 @@ class Operator(metaclass=ABCMeta): def __enter__(self): # Save current directory and move to specific output directory self._orig_dir = os.getcwd() - self.settings.output_dir.mkdir(exist_ok=True) + if not self.settings.output_dir.exists(): + self.settings.output_dir.mkdir() # exist_ok parameter is 3.5+ # In Python 3.6+, chdir accepts a Path directly os.chdir(str(self.settings.output_dir)) From c9abcfc0a1890da0263642e22b3cd9675f28242c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 17 Feb 2018 10:28:24 -0600 Subject: [PATCH 127/212] Make ReactionRates a subclass of ndarray, simplifying mapping dictionaries --- openmc/deplete/chain.py | 41 +++++++-------- openmc/deplete/openmc_wrapper.py | 20 ++++---- openmc/deplete/reaction_rates.py | 86 +++++++++++--------------------- openmc/deplete/results.py | 12 ++--- 4 files changed, 63 insertions(+), 96 deletions(-) diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 846b3af564..2187b04860 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -117,9 +117,7 @@ class Chain(object): List of nuclides in chain. nuclide_dict : OrderedDict of str to int Maps a nuclide name to an index in nuclides. - nuc_to_react_ind : OrderedDict of str to int - Dictionary mapping a nuclide name to an index in ReactionRates. - react_to_ind : OrderedDict of str to int + index_reaction : OrderedDict of str to int Dictionary mapping a reaction name to an index in ReactionRates. """ @@ -127,8 +125,7 @@ class Chain(object): def __init__(self): self.nuclides = [] self.nuclide_dict = OrderedDict() - self.nuc_to_react_ind = OrderedDict() - self.react_to_ind = OrderedDict() + self.index_reaction = OrderedDict() def __contains__(self, nuclide): return nuclide in self.nuclide_dict @@ -155,7 +152,7 @@ class Chain(object): List of ENDF neutron reaction sub-library files """ - depl_chain = cls() + chain = cls() # Create dictionary mapping target to filename reactions = {} @@ -200,8 +197,8 @@ class Chain(object): nuclide = Nuclide() nuclide.name = parent - depl_chain.nuclides.append(nuclide) - depl_chain.nuclide_dict[parent] = idx + chain.nuclides.append(nuclide) + chain.nuclide_dict[parent] = idx if not data.nuclide['stable'] and data.half_life.nominal_value != 0.0: nuclide.half_life = data.half_life.nominal_value @@ -235,8 +232,8 @@ class Chain(object): Z = data.nuclide['atomic_number'] + delta_Z daughter = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) - if name not in depl_chain.react_to_ind: - depl_chain.react_to_ind[name] = reaction_index + if name not in chain.index_reaction: + chain.index_reaction[name] = reaction_index reaction_index += 1 if daughter not in decay_data: @@ -259,8 +256,8 @@ class Chain(object): nuclide.reactions.append( ReactionTuple('fission', 0, q_value, 1.0)) - if 'fission' not in depl_chain.react_to_ind: - depl_chain.react_to_ind['fission'] = reaction_index + if 'fission' not in chain.index_reaction: + chain.index_reaction['fission'] = reaction_index reaction_index += 1 else: missing_fpy.append(parent) @@ -316,7 +313,7 @@ class Chain(object): for vals in missing_fp: print(' {}, E={} eV (total yield={})'.format(*vals)) - return depl_chain + return chain @classmethod def from_xml(cls, filename): @@ -331,7 +328,7 @@ class Chain(object): ---- Allow for branching on capture, etc. """ - depl_chain = cls() + chain = cls() # Load XML tree try: @@ -346,17 +343,17 @@ class Chain(object): reaction_index = 0 for i, nuclide_elem in enumerate(root.findall('nuclide_table')): nuc = Nuclide.from_xml(nuclide_elem) - depl_chain.nuclide_dict[nuc.name] = i + chain.nuclide_dict[nuc.name] = i # Check for reaction paths for rx in nuc.reactions: - if rx.type not in depl_chain.react_to_ind: - depl_chain.react_to_ind[rx.type] = reaction_index + if rx.type not in chain.index_reaction: + chain.index_reaction[rx.type] = reaction_index reaction_index += 1 - depl_chain.nuclides.append(nuc) + chain.nuclides.append(nuc) - return depl_chain + return chain def export_to_xml(self, filename): """Writes a depletion chain XML file. @@ -416,14 +413,14 @@ class Chain(object): k = self.nuclide_dict[target] matrix[k, i] += branch_val - if nuc.name in self.nuc_to_react_ind: + if nuc.name in rates.index_nuc: # Extract all reactions for this nuclide in this cell - nuc_ind = self.nuc_to_react_ind[nuc.name] + nuc_ind = rates.index_nuc[nuc.name] nuc_rates = rates[nuc_ind, :] for r_type, target, _, br in nuc.reactions: # Extract reaction index, and then final reaction rate - r_id = self.react_to_ind[r_type] + r_id = rates.index_rx[r_type] path_rate = nuc_rates[r_id] # Loss term -- make sure we only count loss once for diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index b8b9065276..46d07a23f7 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -369,9 +369,7 @@ class OpenMCOperator(Operator): self.reaction_rates = ReactionRates( self.burn_mat_to_ind, self.burn_nuc_to_ind, - self.chain.react_to_ind) - - self.chain.nuc_to_react_ind = self.burn_nuc_to_ind + self.chain.index_reaction) def form_matrix(self, y, mat): """Forms the depletion matrix. @@ -522,7 +520,7 @@ class OpenMCOperator(Operator): # transmutation. The nuclides for the tally are set later when eval() is # called. tally_dep = openmc.capi.Tally(1) - tally_dep.scores = self.chain.react_to_ind.keys() + tally_dep.scores = self.chain.index_reaction.keys() tally_dep.filters = [mat_filter] def total_density_list(self): @@ -579,11 +577,11 @@ class OpenMCOperator(Operator): # Extract tally bins materials = list(self.mat_tally_ind.keys()) nuclides = openmc.capi.tallies[1].nuclides - reactions = list(self.chain.react_to_ind.keys()) + reactions = list(self.chain.index_reaction.keys()) # Form fast map - nuc_ind = [rates.nuc_to_ind[nuc] for nuc in nuclides] - react_ind = [rates.react_to_ind[react] for react in reactions] + nuc_ind = [rates.index_nuc[nuc] for nuc in nuclides] + react_ind = [rates.index_rx[react] for react in reactions] # Compute fission power # TODO : improve this calculation @@ -598,13 +596,13 @@ class OpenMCOperator(Operator): rates_expanded = np.zeros((rates.n_nuc, rates.n_react)) number = np.zeros(rates.n_nuc) - fission_ind = rates.react_to_ind["fission"] + fission_ind = rates.index_rx["fission"] for nuclide in self.chain.nuclides: - if nuclide.name in rates.nuc_to_ind: + if nuclide.name in rates.index_nuc: for rx in nuclide.reactions: if rx.type == 'fission': - ind = rates.nuc_to_ind[nuclide.name] + ind = rates.index_nuc[nuclide.name] fission_Q[ind] = rx.Q break @@ -637,7 +635,7 @@ class OpenMCOperator(Operator): for react in react_ind: rates_expanded[i_nuc_results, react] /= number[i_nuc_results] - rates.rates[i, :, :] = rates_expanded + rates[i, :, :] = rates_expanded # Reduce energy produced from all processes energy = comm.allreduce(energy) diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index e8bab101bf..b437773826 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -6,7 +6,7 @@ An ndarray to store reaction rates with string, integer, or slice indexing. import numpy as np -class ReactionRates(object): +class ReactionRates(np.ndarray): """ReactionRates class. An ndarray to store reaction rates with string, integer, or slice indexing. @@ -38,76 +38,48 @@ class ReactionRates(object): Array storing rates indexed by the above dictionaries. """ - def __init__(self, mat_to_ind, nuc_to_ind, react_to_ind): + def __new__(cls, index_mat, index_nuc, index_rx): + # Create appropriately-sized zeroed-out ndarray + shape = (len(index_mat), len(index_nuc), len(index_rx)) + obj = super().__new__(cls, shape) + obj[:] = 0.0 - self.mat_to_ind = mat_to_ind - self.nuc_to_ind = nuc_to_ind - self.react_to_ind = react_to_ind + # Add mapping attributes + obj.index_mat = index_mat + obj.index_nuc = index_nuc + obj.index_rx = index_rx - self.rates = np.zeros((self.n_mat, self.n_nuc, self.n_react)) + return obj - def __getitem__(self, pos): - """Retrieves an item from reaction_rates. + def __array_finalize__(self, obj): + if obj is None: + return + self.index_mat = getattr(obj, 'index_mat', None) + self.index_nuc = getattr(obj, 'index_nuc', None) + self.index_rx = getattr(obj, 'index_rx', None) - Parameters - ---------- - pos : tuple - A three-length tuple containing a material index, a nuc index, and a - reaction index. These indexes can be strings (which get converted - to integers via the dictionaries), integers used directly, or - slices. + def __reduce__(self): + state = super().__reduce__() + new_state = state[2] + (self.index_mat, self.index_nuc, self.index_rx) + return (state[0], state[1], new_state) - Returns - ------- - numpy.array - The value indexed from self.rates. - """ - - mat, nuc, react = pos - if isinstance(mat, str): - mat = self.mat_to_ind[mat] - if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] - if isinstance(react, str): - react = self.react_to_ind[react] - - return self.rates[mat, nuc, react] - - def __setitem__(self, pos, val): - """Sets an item from reaction_rates. - - Parameters - ---------- - pos : tuple - A three-length tuple containing a material index, a nuc index, and a - reaction index. These indexes can be strings (which get converted - to integers via the dictionaries), integers used directly, or - slices. - val : float - The value to set the array to. - """ - - mat, nuc, react = pos - if isinstance(mat, str): - mat = self.mat_to_ind[mat] - if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] - if isinstance(react, str): - react = self.react_to_ind[react] - - self.rates[mat, nuc, react] = val + def __setstate__(self, state): + self.index_mat = state[-3] + self.index_nuc = state[-2] + self.index_rx = state[-1] + super().__setstate__(state[0:-3]) @property def n_mat(self): """Number of cells.""" - return len(self.mat_to_ind) + return len(self.index_mat) @property def n_nuc(self): """Number of nucs.""" - return len(self.nuc_to_ind) + return len(self.index_nuc) @property def n_react(self): """Number of reactions.""" - return len(self.react_to_ind) + return len(self.index_rx) diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 37c4b6e921..4a5ca24352 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -180,11 +180,11 @@ class Results(object): mat_int = sorted([int(mat) for mat in self.mat_to_hdf5_ind]) mat_list = [str(mat) for mat in mat_int] nuc_list = sorted(self.nuc_to_ind.keys()) - rxn_list = sorted(self.rates[0].react_to_ind.keys()) + rxn_list = sorted(self.rates[0].index_rx.keys()) n_mats = self.n_hdf5_mats n_nuc_number = len(nuc_list) - n_nuc_rxn = len(self.rates[0].nuc_to_ind) + n_nuc_rxn = len(self.rates[0].index_nuc) n_rxn = len(rxn_list) n_stages = self.n_stages @@ -200,14 +200,14 @@ class Results(object): for nuc in nuc_list: nuc_single_group = nuc_group.create_group(nuc) nuc_single_group.attrs["atom number index"] = self.nuc_to_ind[nuc] - if nuc in self.rates[0].nuc_to_ind: - nuc_single_group.attrs["reaction rate index"] = self.rates[0].nuc_to_ind[nuc] + if nuc in self.rates[0].index_nuc: + nuc_single_group.attrs["reaction rate index"] = self.rates[0].index_nuc[nuc] rxn_group = handle.create_group("reactions") for rxn in rxn_list: rxn_single_group = rxn_group.create_group(rxn) - rxn_single_group.attrs["index"] = self.rates[0].react_to_ind[rxn] + rxn_single_group.attrs["index"] = self.rates[0].index_rx[rxn] # Construct array storage @@ -341,7 +341,7 @@ class Results(object): for i in range(results.n_stages): rate = ReactionRates(results.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) - rate.rates = handle["/reaction rates"][index, i, :, :, :] + rate[:] = handle["/reaction rates"][index, i, :, :, :] results.rates.append(rate) return results From 5c4ea0d640a41daa9da0a65d134525a7a6589a09 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 17 Feb 2018 14:31:04 -0600 Subject: [PATCH 128/212] Replace Chain.index_reaction with Chain.reactions. Now the ReactionRates controls all the indexing needed to build a depletion matrix. Got all tests fixed here too. Decided to add get/set methods on ReactionRates which take strings. --- openmc/deplete/chain.py | 27 ++++------ openmc/deplete/openmc_wrapper.py | 12 ++--- openmc/deplete/reaction_rates.py | 59 +++++++++++++++++---- openmc/deplete/utilities.py | 48 ++++++++--------- tests/unit_tests/test_deplete_chain.py | 57 ++++++++++---------- tests/unit_tests/test_deplete_integrator.py | 6 +-- tests/unit_tests/test_deplete_reaction.py | 51 +++++++++--------- 7 files changed, 147 insertions(+), 113 deletions(-) diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 2187b04860..2af64e172a 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -113,19 +113,19 @@ class Chain(object): Attributes ---------- - nuclides : list of Nuclide - List of nuclides in chain. + nuclides : list of openmc.deplete.Nuclide + Nuclides present in the chain. + reactions : list of str + Reactions that are tracked in the depletion chain nuclide_dict : OrderedDict of str to int Maps a nuclide name to an index in nuclides. - index_reaction : OrderedDict of str to int - Dictionary mapping a reaction name to an index in ReactionRates. """ def __init__(self): self.nuclides = [] + self.reactions = [] self.nuclide_dict = OrderedDict() - self.index_reaction = OrderedDict() def __contains__(self, nuclide): return nuclide in self.nuclide_dict @@ -190,7 +190,6 @@ class Chain(object): missing_fpy = [] missing_fp = [] - reaction_index = 0 for idx, parent in enumerate(sorted(decay_data, key=_get_zai)): data = decay_data[parent] @@ -232,9 +231,8 @@ class Chain(object): Z = data.nuclide['atomic_number'] + delta_Z daughter = '{}{}'.format(openmc.data.ATOMIC_SYMBOL[Z], A) - if name not in chain.index_reaction: - chain.index_reaction[name] = reaction_index - reaction_index += 1 + if name not in chain.reactions: + chain.reactions.append(name) if daughter not in decay_data: missing_rx_product.append((parent, name, daughter)) @@ -256,9 +254,8 @@ class Chain(object): nuclide.reactions.append( ReactionTuple('fission', 0, q_value, 1.0)) - if 'fission' not in chain.index_reaction: - chain.index_reaction['fission'] = reaction_index - reaction_index += 1 + if 'fission' not in chain.reactions: + chain.reactions.append('fission') else: missing_fpy.append(parent) @@ -340,16 +337,14 @@ class Chain(object): print('Decay chain "', filename, '" is invalid.') raise - reaction_index = 0 for i, nuclide_elem in enumerate(root.findall('nuclide_table')): nuc = Nuclide.from_xml(nuclide_elem) chain.nuclide_dict[nuc.name] = i # Check for reaction paths for rx in nuc.reactions: - if rx.type not in chain.index_reaction: - chain.index_reaction[rx.type] = reaction_index - reaction_index += 1 + if rx.type not in chain.reactions: + chain.reactions.append(rx.type) chain.nuclides.append(nuc) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 46d07a23f7..c95170a461 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -366,10 +366,11 @@ class OpenMCOperator(Operator): def initialize_reaction_rates(self): """Create reaction rates object. """ + # Create dictionary to map reactions to indices + index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} + self.reaction_rates = ReactionRates( - self.burn_mat_to_ind, - self.burn_nuc_to_ind, - self.chain.index_reaction) + self.burn_mat_to_ind, self.burn_nuc_to_ind, index_rx) def form_matrix(self, y, mat): """Forms the depletion matrix. @@ -520,7 +521,7 @@ class OpenMCOperator(Operator): # transmutation. The nuclides for the tally are set later when eval() is # called. tally_dep = openmc.capi.Tally(1) - tally_dep.scores = self.chain.index_reaction.keys() + tally_dep.scores = self.chain.reactions tally_dep.filters = [mat_filter] def total_density_list(self): @@ -577,11 +578,10 @@ class OpenMCOperator(Operator): # Extract tally bins materials = list(self.mat_tally_ind.keys()) nuclides = openmc.capi.tallies[1].nuclides - reactions = list(self.chain.index_reaction.keys()) # Form fast map nuc_ind = [rates.index_nuc[nuc] for nuc in nuclides] - react_ind = [rates.index_rx[react] for react in reactions] + react_ind = [rates.index_rx[react] for react in self.chain.reactions] # Compute fission power # TODO : improve this calculation diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index b437773826..a479085174 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -13,20 +13,20 @@ class ReactionRates(np.ndarray): Parameters ---------- - mat_to_ind : OrderedDict of str to int + index_mat : OrderedDict of str to int A dictionary mapping material ID as string to index. - nuc_to_ind : OrderedDict of str to int + index_nuc : OrderedDict of str to int A dictionary mapping nuclide name as string to index. - react_to_ind : OrderedDict of str to int + index_rx : OrderedDict of str to int A dictionary mapping reaction name as string to index. Attributes ---------- - mat_to_ind : OrderedDict of str to int + index_mat : OrderedDict of str to int A dictionary mapping material ID as string to index. - nuc_to_ind : OrderedDict of str to int + index_nuc : OrderedDict of str to int A dictionary mapping nuclide name as string to index. - react_to_ind : OrderedDict of str to int + index_rx : OrderedDict of str to int A dictionary mapping reaction name as string to index. n_mat : int Number of materials. @@ -34,10 +34,8 @@ class ReactionRates(np.ndarray): Number of nucs. n_react : int Number of reactions. - rates : numpy.array - Array storing rates indexed by the above dictionaries. - """ + """ def __new__(cls, index_mat, index_nuc, index_rx): # Create appropriately-sized zeroed-out ndarray shape = (len(index_mat), len(index_nuc), len(index_rx)) @@ -83,3 +81,46 @@ class ReactionRates(np.ndarray): def n_react(self): """Number of reactions.""" return len(self.index_rx) + + def get(self, mat, nuc, rx): + """Get reaction rate by material/nuclide/reaction + + Parameters + ---------- + mat : str + Material ID as a string + nuc : str + Nuclide name + rx : str + Name of the reaction + + Returns + ------- + float + Reaction rate corresponding to given material, nuclide, and reaction + + """ + mat = self.index_mat[mat] + nuc = self.index_nuc[nuc] + rx = self.index_rx[rx] + return self[mat, nuc, rx] + + def set(self, mat, nuc, rx, value): + """Set reaction rate by material/nuclide/reaction + + Parameters + ---------- + mat : str + Material ID as a string + nuc : str + Nuclide name + rx : str + Name of the reaction + value : float + Corresponding reaction rate to set + + """ + mat = self.index_mat[mat] + nuc = self.index_nuc[nuc] + rx = self.index_rx[rx] + self[mat, nuc, rx] = value diff --git a/openmc/deplete/utilities.py b/openmc/deplete/utilities.py index 5433edce44..d155f321d9 100644 --- a/openmc/deplete/utilities.py +++ b/openmc/deplete/utilities.py @@ -7,26 +7,26 @@ the results module. import numpy as np -def evaluate_single_nuclide(results, cell, nuc): - """Evaluates a single nuclide in a single cell from a results list. +def evaluate_single_nuclide(results, mat, nuc): + """Evaluates a single nuclide in a single material from a results list. Parameters ---------- results : list of results The results to extract data from. Must be sorted and continuous. - cell : str - Cell name to evaluate + mat : str + Material name to evaluate nuc : str Nuclide name to evaluate Returns ------- - time : numpy.array - Time vector. - concentration : numpy.array - Total number of atoms in the cell. - """ + time : numpy.ndarray + Time vector + concentration : numpy.ndarray + Total number of atoms in the material + """ n_points = len(results) time = np.zeros(n_points) concentration = np.zeros(n_points) @@ -34,39 +34,39 @@ def evaluate_single_nuclide(results, cell, nuc): # Evaluate value in each region for i, result in enumerate(results): time[i] = result.time[0] - concentration[i] = result[0, cell, nuc] + concentration[i] = result[0, mat, nuc] return time, concentration -def evaluate_reaction_rate(results, cell, nuc, rxn): - """Evaluates a single nuclide reaction rate in a single cell from a results list. +def evaluate_reaction_rate(results, mat, nuc, rx): + """Return reaction rate in a single material/nuclide from a results list. Parameters ---------- - results : list of Results + results : list of openmc.deplete.Results The results to extract data from. Must be sorted and continuous. - cell : str - Cell name to evaluate + mat : str + Material name to evaluate nuc : str Nuclide name to evaluate - rxn : str + rx : str Reaction rate to evaluate Returns ------- - time : numpy.array + time : numpy.ndarray Time vector. - rate : numpy.array + rate : numpy.ndarray Reaction rate. - """ + """ n_points = len(results) time = np.zeros(n_points) rate = np.zeros(n_points) # Evaluate value in each region for i, result in enumerate(results): time[i] = result.time[0] - rate[i] = result.rates[0][cell, nuc, rxn] * result[0, cell, nuc] + rate[i] = result.rates[0].get(mat, nuc, rx) * result[0, mat, nuc] return time, rate @@ -76,17 +76,17 @@ def evaluate_eigenvalue(results): Parameters ---------- - results : list of Results + results : list of openmc.deplete.Results The results to extract data from. Must be sorted and continuous. Returns ------- - time : numpy.array + time : numpy.ndarray Time vector. - eigenvalue : numpy.array + eigenvalue : numpy.ndarray Eigenvalue. - """ + """ n_points = len(results) time = np.zeros(n_points) eigenvalue = np.zeros(n_points) diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 3a065fb46f..ae900e62d7 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -13,19 +13,18 @@ _test_filename = str(Path(__file__).parents[2] / 'chains' / 'chain_test.xml') def test_init(): """Test depletion chain initialization.""" - dep = Chain() + chain = Chain() - assert isinstance(dep.nuclides, list) - assert isinstance(dep.nuclide_dict, Mapping) - assert isinstance(dep.react_to_ind, Mapping) + assert isinstance(chain.nuclides, list) + assert isinstance(chain.nuclide_dict, Mapping) def test_len(): """Test depletion chain length.""" - dep = Chain() - dep.nuclides = ["NucA", "NucB", "NucC"] + chain = Chain() + chain.nuclides = ["NucA", "NucB", "NucC"] - assert len(dep) == 3 + assert len(chain) == 3 def test_from_endf(): @@ -40,13 +39,13 @@ def test_from_xml(): # the components external to depletion_chain.py are simple storage # types. - dep = Chain.from_xml(_test_filename) + chain = Chain.from_xml(_test_filename) # Basic checks - assert len(dep) == 3 + assert len(chain) == 3 # A tests - nuc = dep["A"] + nuc = chain["A"] assert nuc.name == "A" assert nuc.half_life == 2.36520E+04 @@ -61,7 +60,7 @@ def test_from_xml(): assert [r.branching_ratio for r in nuc.reactions] == [1.0] # B tests - nuc = dep["B"] + nuc = chain["B"] assert nuc.name == "B" assert nuc.half_life == 3.29040E+04 @@ -76,7 +75,7 @@ def test_from_xml(): assert [r.branching_ratio for r in nuc.reactions] == [1.0] # C tests - nuc = dep["C"] + nuc = chain["C"] assert nuc.name == "C" assert nuc.n_decay_modes == 0 @@ -135,22 +134,20 @@ def test_form_matrix(): """ Using chain_test, and a dummy reaction rate, compute the matrix. """ # Relies on test_from_xml passing. - dep = Chain.from_xml(_test_filename) + chain = Chain.from_xml(_test_filename) - cell_ind = {"10000": 0, "10001": 1} + mat_ind = {"10000": 0, "10001": 1} nuc_ind = {"A": 0, "B": 1, "C": 2} - react_ind = dep.react_to_ind + react_ind = {rx: i for i, rx in enumerate(chain.reactions)} - react = reaction_rates.ReactionRates(cell_ind, nuc_ind, react_ind) + react = reaction_rates.ReactionRates(mat_ind, nuc_ind, react_ind) - dep.nuc_to_react_ind = nuc_ind + react.set("10000", "C", "fission", 1.0) + react.set("10000", "A", "(n,gamma)", 2.0) + react.set("10000", "B", "(n,gamma)", 3.0) + react.set("10000", "C", "(n,gamma)", 4.0) - react["10000", "C", "fission"] = 1.0 - react["10000", "A", "(n,gamma)"] = 2.0 - react["10000", "B", "(n,gamma)"] = 3.0 - react["10000", "C", "(n,gamma)"] = 4.0 - - mat = dep.form_matrix(react[0, :, :]) + mat = chain.form_matrix(react[0, :, :]) # Loss A, decay, (n, gamma) mat00 = -np.log(2) / 2.36520E+04 - 2 # A -> B, decay, 0.6 branching ratio @@ -185,11 +182,11 @@ def test_form_matrix(): def test_getitem(): """ Test nuc_by_ind converter function. """ - dep = Chain() - dep.nuclides = ["NucA", "NucB", "NucC"] - dep.nuclide_dict = {nuc: dep.nuclides.index(nuc) - for nuc in dep.nuclides} + chain = Chain() + chain.nuclides = ["NucA", "NucB", "NucC"] + chain.nuclide_dict = {nuc: chain.nuclides.index(nuc) + for nuc in chain.nuclides} - assert "NucA" == dep["NucA"] - assert "NucB" == dep["NucB"] - assert "NucC" == dep["NucC"] + assert "NucA" == chain["NucA"] + assert "NucB" == chain["NucB"] + assert "NucC" == chain["NucC"] diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index 59d08b4842..78dd6bcef2 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -86,10 +86,8 @@ def test_save_results(run_in_tmpdir): for nuc_i, nuc in enumerate(nuc_list): assert res[0][i, mat, nuc] == x1[i][mat_i][nuc_i] assert res[1][i, mat, nuc] == x2[i][mat_i][nuc_i] - np.testing.assert_array_equal(res[0].rates[i][mat, nuc, :], - rate1[i][mat, nuc, :]) - np.testing.assert_array_equal(res[1].rates[i][mat, nuc, :], - rate2[i][mat, nuc, :]) + np.testing.assert_array_equal(res[0].rates[i], rate1[i]) + np.testing.assert_array_equal(res[1].rates[i], rate2[i]) np.testing.assert_array_equal(res[0].k, eigvl1) np.testing.assert_array_equal(res[0].time, t1) diff --git a/tests/unit_tests/test_deplete_reaction.py b/tests/unit_tests/test_deplete_reaction.py index a98535e1d8..de628f8c66 100644 --- a/tests/unit_tests/test_deplete_reaction.py +++ b/tests/unit_tests/test_deplete_reaction.py @@ -1,35 +1,38 @@ """Tests for the openmc.deplete.ReactionRates class.""" -from openmc.deplete import reaction_rates +import numpy as np +from openmc.deplete import ReactionRates -def test_indexing(): - """Tests the __getitem__ and __setitem__ routines simultaneously.""" +def test_get_set(): + """Tests the get/set methods.""" mat_to_ind = {"10000" : 0, "10001" : 1} nuc_to_ind = {"U238" : 0, "U235" : 1} react_to_ind = {"fission" : 0, "(n,gamma)" : 1} - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + assert rates.shape == (2, 2, 2) + assert np.all(rates == 0.0) - rates["10000", "U238", "fission"] = 1.0 - rates["10001", "U238", "fission"] = 2.0 - rates["10000", "U235", "fission"] = 3.0 - rates["10001", "U235", "fission"] = 4.0 - rates["10000", "U238", "(n,gamma)"] = 5.0 - rates["10001", "U238", "(n,gamma)"] = 6.0 - rates["10000", "U235", "(n,gamma)"] = 7.0 - rates["10001", "U235", "(n,gamma)"] = 8.0 + rates.set("10000", "U238", "fission", 1.0) + rates.set("10001", "U238", "fission", 2.0) + rates.set("10000", "U235", "fission", 3.0) + rates.set("10001", "U235", "fission", 4.0) + rates.set("10000", "U238", "(n,gamma)", 5.0) + rates.set("10001", "U238", "(n,gamma)", 6.0) + rates.set("10000", "U235", "(n,gamma)", 7.0) + rates.set("10001", "U235", "(n,gamma)", 8.0) # String indexing - assert rates["10000", "U238", "fission"] == 1.0 - assert rates["10001", "U238", "fission"] == 2.0 - assert rates["10000", "U235", "fission"] == 3.0 - assert rates["10001", "U235", "fission"] == 4.0 - assert rates["10000", "U238", "(n,gamma)"] == 5.0 - assert rates["10001", "U238", "(n,gamma)"] == 6.0 - assert rates["10000", "U235", "(n,gamma)"] == 7.0 - assert rates["10001", "U235", "(n,gamma)"] == 8.0 + assert rates.get("10000", "U238", "fission") == 1.0 + assert rates.get("10001", "U238", "fission") == 2.0 + assert rates.get("10000", "U235", "fission") == 3.0 + assert rates.get("10001", "U235", "fission") == 4.0 + assert rates.get("10000", "U238", "(n,gamma)") == 5.0 + assert rates.get("10001", "U238", "(n,gamma)") == 6.0 + assert rates.get("10000", "U235", "(n,gamma)") == 7.0 + assert rates.get("10001", "U235", "(n,gamma)") == 8.0 # Int indexing assert rates[0, 0, 0] == 1.0 @@ -44,7 +47,7 @@ def test_indexing(): rates[0, 0, 0] = 5.0 assert rates[0, 0, 0] == 5.0 - assert rates["10000", "U238", "fission"] == 5.0 + assert rates.get("10000", "U238", "fission") == 5.0 def test_n_mat(): @@ -53,7 +56,7 @@ def test_n_mat(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) assert rates.n_mat == 2 @@ -64,7 +67,7 @@ def test_n_nuc(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) assert rates.n_nuc == 3 @@ -75,6 +78,6 @@ def test_n_react(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - rates = reaction_rates.ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) assert rates.n_react == 4 From 9ec044ec2ed49d44470182a628770bf3e31f42ce Mon Sep 17 00:00:00 2001 From: walshjon Date: Sat, 17 Feb 2018 14:09:37 -0800 Subject: [PATCH 129/212] disallow target energy greater than is used in SIGMA1 --- src/physics.F90 | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/physics.F90 b/src/physics.F90 index 53a2cc2320..6c267d8758 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -925,11 +925,14 @@ contains maxval(nuc % elastic_0K(i_E_low + 1 : i_E_up)), xs_up) DBRC_REJECT_LOOP: do - ! sample target velocity with the constant cross section (cxs) approx. - call sample_cxs_target_velocity(nuc, v_target, E, uvw, kT) - + TARGET_ENERGY_LOOP: do + ! sample target velocity with the constant cross section (cxs) approx. + call sample_cxs_target_velocity(nuc, v_target, E, uvw, kT) + E_rel = dot_product((v_neut - v_target), (v_neut - v_target)) + if (E_rel < E_up) exit TARGET_ENERGY_LOOP + end do TARGET_ENERGY_LOOP + ! perform Doppler broadening rejection correction (dbrc) - E_rel = dot_product((v_neut - v_target), (v_neut - v_target)) xs_0K = elastic_xs_0K(E_rel, nuc) R = xs_0K / xs_max if (prn() < R) exit DBRC_REJECT_LOOP From 7704390a3b3e0f5aef46df8b68041a9f022f637d Mon Sep 17 00:00:00 2001 From: walshjon Date: Sat, 17 Feb 2018 15:39:55 -0800 Subject: [PATCH 130/212] remove . --- src/physics.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/physics.F90 b/src/physics.F90 index 6c267d8758..b614b81851 100644 --- a/src/physics.F90 +++ b/src/physics.F90 @@ -931,7 +931,7 @@ contains E_rel = dot_product((v_neut - v_target), (v_neut - v_target)) if (E_rel < E_up) exit TARGET_ENERGY_LOOP end do TARGET_ENERGY_LOOP - + ! perform Doppler broadening rejection correction (dbrc) xs_0K = elastic_xs_0K(E_rel, nuc) R = xs_0K / xs_max From 82fea220c40615bd44b61d120f7059b7efed3aaf Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 07:23:26 -0600 Subject: [PATCH 131/212] Use get_all_materials() to simplify logic --- openmc/deplete/openmc_wrapper.py | 71 ++++++++++---------------------- 1 file changed, 21 insertions(+), 50 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index c95170a461..9a895a5081 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -104,7 +104,7 @@ class OpenMCOperator(Operator): ---------- geometry : openmc.Geometry The OpenMC geometry object. - settings : OpenMCSettings + settings : openmc.deplete.OpenMCSettings Settings object. Attributes @@ -130,8 +130,8 @@ class OpenMCOperator(Operator): Number of nuclides considered in the decay chain. mat_tally_ind : OrderedDict of str to int Dictionary mapping material ID to index in tally. - """ + """ def __init__(self, geometry, settings): super().__init__(settings) @@ -170,8 +170,10 @@ class OpenMCOperator(Operator): # Extract number densities from the geometry self.extract_number(mat_burn, mat_not_burn, volume, nuc_dict) - # Create reaction rate tables - self.initialize_reaction_rates() + # Create reaction rates array + index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} + self.reaction_rates = ReactionRates( + self.burn_mat_to_ind, self.burn_nuc_to_ind, index_rx) def __call__(self, vec, print_out=True): """Runs a simulation. @@ -243,35 +245,17 @@ class OpenMCOperator(Operator): volume = OrderedDict() # Iterate once through the geometry to get dictionaries - cells = self.geometry.get_all_material_cells() - for cell in cells.values(): - if isinstance(cell.fill, openmc.Material): - mat = cell.fill - for nuclide in mat.get_nuclide_densities(): - nuc_set.add(nuclide) - if mat.depletable: - mat_burn.add(str(mat.id)) - volume[str(mat.id)] = mat.volume - else: - mat_not_burn.add(str(mat.id)) + for mat in self.geometry.get_all_materials().values(): + for nuclide in mat.get_nuclide_densities(): + nuc_set.add(nuclide) + if mat.depletable: + mat_burn.add(str(mat.id)) + if mat.volume is None: + raise RuntimeError("Volume not specified for depletable " + "material with ID={}.".format(mat.id)) + volume[str(mat.id)] = mat.volume else: - for mat in cell.fill: - for nuclide in mat.get_nuclide_densities(): - nuc_set.add(nuclide) - if mat.depletable: - mat_burn.add(str(mat.id)) - volume[str(mat.id)] = mat.volume - else: - mat_not_burn.add(str(mat.id)) - - need_vol = [] - - for mat_id in volume: - if volume[mat_id] is None: - need_vol.append(mat_id) - - if need_vol: - exit("Need volumes for materials: " + str(need_vol)) + mat_not_burn.add(str(mat.id)) # Sort the sets mat_burn = sorted(mat_burn, key=int) @@ -334,18 +318,13 @@ class OpenMCOperator(Operator): if self.settings.dilute_initial != 0.0: for nuc in self.burn_nuc_to_ind: - self.number.set_atom_density(np.s_[:], nuc, self.settings.dilute_initial) + self.number.set_atom_density(np.s_[:], nuc, + self.settings.dilute_initial) # Now extract the number densities and store - cells = self.geometry.get_all_material_cells() - for cell in cells.values(): - if isinstance(cell.fill, openmc.Material): - if str(cell.fill.id) in mat_dict: - self.set_number_from_mat(cell.fill) - else: - for mat in cell.fill: - if str(mat.id) in mat_dict: - self.set_number_from_mat(mat) + for mat in self.geometry.get_all_materials().values(): + if str(mat.id) in mat_dict: + self.set_number_from_mat(mat) def set_number_from_mat(self, mat): """Extracts material and number densities from openmc.Material @@ -364,14 +343,6 @@ class OpenMCOperator(Operator): number = nuc_dens[nuclide][1] * 1.0e24 self.number.set_atom_density(mat_id, nuclide, number) - def initialize_reaction_rates(self): - """Create reaction rates object. """ - # Create dictionary to map reactions to indices - index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} - - self.reaction_rates = ReactionRates( - self.burn_mat_to_ind, self.burn_nuc_to_ind, index_rx) - def form_matrix(self, y, mat): """Forms the depletion matrix. From afd4ad61b0717c3566053bc6ca294df4ee8cde59 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 08:53:39 -0600 Subject: [PATCH 132/212] Support --update for depletion regression test --- openmc/deplete/results.py | 2 +- tests/regression_tests/test_deplete_full.py | 27 +++++++++++++-------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 4a5ca24352..539ce5dd67 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -419,7 +419,7 @@ def read_results(filename): The result objects. """ - with h5py.File(filename, "r") as fh: + with h5py.File(str(filename), "r") as fh: assert fh["version"].value == RESULTS_VERSION # Get number of results stored diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index c809ba0536..6033e3f75a 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -11,6 +11,7 @@ import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities +from tests.regression_tests import config from .example_geometry import generate_problem @@ -59,33 +60,39 @@ def test_full(run_in_tmpdir): # Perform simulation using the predictor algorithm openmc.deplete.integrator.predictor(op) - # Load the files - res_test = results.read_results(settings.output_dir / "depletion_results.h5") + # Get path to test and reference results + path_test = settings.output_dir / 'depletion_results.h5' + path_reference = Path(__file__).with_name('test_reference.h5') - # Load the reference - filename = str(Path(__file__).with_name('test_reference.h5')) - res_old = results.read_results(filename) + # If updating results, do so and return + if config['update']: + shutil.copyfile(str(path_test), str(path_reference)) + return + + # Load the reference/test results + res_test = results.read_results(path_test) + res_ref = results.read_results(path_reference) # Assert same mats - for mat in res_old[0].mat_to_ind: + for mat in res_ref[0].mat_to_ind: assert mat in res_test[0].mat_to_ind, \ "Material {} not in new results.".format(mat) - for nuc in res_old[0].nuc_to_ind: + for nuc in res_ref[0].nuc_to_ind: assert nuc in res_test[0].nuc_to_ind, \ "Nuclide {} not in new results.".format(nuc) for mat in res_test[0].mat_to_ind: - assert mat in res_old[0].mat_to_ind, \ + assert mat in res_ref[0].mat_to_ind, \ "Material {} not in old results.".format(mat) for nuc in res_test[0].nuc_to_ind: - assert nuc in res_old[0].nuc_to_ind, \ + assert nuc in res_ref[0].nuc_to_ind, \ "Nuclide {} not in old results.".format(nuc) tol = 1.0e-6 for mat in res_test[0].mat_to_ind: for nuc in res_test[0].nuc_to_ind: _, y_test = utilities.evaluate_single_nuclide(res_test, mat, nuc) - _, y_old = utilities.evaluate_single_nuclide(res_old, mat, nuc) + _, y_old = utilities.evaluate_single_nuclide(res_ref, mat, nuc) # Test each point correct = True From f113205ab91bb28976314d2cc0f306186410f9cd Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 09:15:09 -0600 Subject: [PATCH 133/212] Don't update non-depletable materials (changes test results) --- openmc/deplete/openmc_wrapper.py | 3 ++ .../test_deplete_utilities.py | 39 +++++++++--------- tests/regression_tests/test_reference.h5 | Bin 231608 -> 162120 bytes 3 files changed, 23 insertions(+), 19 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 9a895a5081..e5eaf52dc0 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -397,6 +397,9 @@ class OpenMCOperator(Operator): number_i = comm.bcast(self.number, root=rank) for mat in number_i.mat_to_ind: + if number_i.mat_to_ind[mat] >= number_i.n_mat_burn: + continue + nuclides = [] densities = [] for nuc in number_i.nuc_to_ind: diff --git a/tests/regression_tests/test_deplete_utilities.py b/tests/regression_tests/test_deplete_utilities.py index f9d34aa75a..f38129cc79 100644 --- a/tests/regression_tests/test_deplete_utilities.py +++ b/tests/regression_tests/test_deplete_utilities.py @@ -20,35 +20,36 @@ def res(): def test_evaluate_single_nuclide(res): """Tests evaluating single nuclide utility code.""" - x, y = utilities.evaluate_single_nuclide(res, "1", "Xe135") + t, n = utilities.evaluate_single_nuclide(res, "1", "Xe135") - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - y_ref = [6.6747328233649218e+08, 3.5519299354458244e+14, - 3.4599104054580338e+14, 3.3821165110278112e+14] + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + n_ref = [6.6747328233649218e+08, 3.5421791038348462e+14, + 3.6208592242443462e+14, 3.3799758969347038e+14] - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, y_ref) + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(n, n_ref) def test_evaluate_reaction_rate(res): """Tests evaluating reaction rate utility code.""" - x, y = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") + t, r = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - xe_ref = np.array([6.6747328233649218e+08, 3.5519299354458244e+14, - 3.4599104054580338e+14, 3.3821165110278112e+14]) - r_ref = np.array([4.0643598574337784e-05, 4.1457730544386974e-05, - 3.4121248544056681e-05, 3.9204686657643301e-05]) + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + n_ref = np.array([6.6747328233649218e+08, 3.5421791038348462e+14, + 3.6208592242443462e+14, 3.3799758969347038e+14]) + xs_ref = np.array([4.0594392323131994e-05, 3.9249546927524987e-05, + 3.8394587728581798e-05, 4.1521845978371697e-05]) - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, xe_ref * r_ref) + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(r, n_ref * xs_ref) def test_evaluate_eigenvalue(res): """Tests evaluating eigenvalue.""" - x, y = utilities.evaluate_eigenvalue(res) + t, k = utilities.evaluate_eigenvalue(res) - x_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] - y_ref = [1.1921986054449838, 1.1712785643938586, 1.1927099024502694, 1.2269183590698847] + t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] + k_ref = [1.181281798790367, 1.1798750921988739, 1.1965943696058159, + 1.2207119847790813] - np.testing.assert_array_equal(x, x_ref) - np.testing.assert_array_equal(y, y_ref) + np.testing.assert_array_equal(t, t_ref) + np.testing.assert_array_equal(k, k_ref) diff --git a/tests/regression_tests/test_reference.h5 b/tests/regression_tests/test_reference.h5 index f832e3e2635c8d25a09609c38830227a3a551958..6e724c597107560c4155a257f4e854210f36f08e 100644 GIT binary patch literal 162120 zcmeEv2|QKZ*Z(!E%u1S#g;M4Wo#Q$OX%K1Bj8cdUr8Fy)22rUr5K2@k4TQ+msF6z1 zY^IDEN>cvkK4+i1bKh>yqhDUn|NWhw&tspp&)RFRz1I4!z4tl$-n-q(+)}*vz}^h@ zKT%PJAVcb}OX^Pt_-D0-|F0^FrtUj{3qDW=gEE0+XYl>?AA=ze>ZO5vZocVu78VSG zmy%DFpcz9;kh~J5D(LdR$^upvX144BCxKCWfzog)6?vfI4;Oq4VInGtf1n#a1{r}= zuL49ov#+IyYVr<~&CL)ZD0V$RKmT8>q67li7Xo|^AcR4|W+wj0{2+I6`HndZMi_bH zU-oy}6dQB44eWtlYPNq3kEfPW;EtaVc|mbU1DYj5)++$M)S)B?#a9Gqh9X(R1bm`X zC=O7;RagO9-sabQT7XXh$fvj)aPmsZk}O>SU)A5l8|7660WO8ONM3o7+b(2Yl;W8e zTV+VW4nTecMqc;>I(jO3LHWVnk)%_>eFrb{q7cw7o5+g>Kzr>bFQkBB{31zOfw~V2 zXbhVkaPo}lfIL*6qr9!#mO6nW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EPf(ZY-A!4{pTFXm+)MeO7U!`?-P?jgBA|@R(ik2*w3bd1AHJ~(&ZTI&J1us zAMgWRjxo;;omU6^L6>9Xm4BSzVHP0kU0OVoed6B-A~XJZZazHx6SItFHv`ybm4D{^ zCjKFDL*nM|5kvcw8E%BEhX*%h7BssZRf&yC2>RI=GS5Ij~bZaCfIg(aHGG9X4e+jXB9VkzX><=KCu8aXsMuYrT1%$ z{cIUHpbYXQU5>Htd=3scgM3bxW6ZNdeFfkTx*Q{~{Nn@>Qd1NK?P zjRA?9?;arg#NP^&|DlW-ZaiIw2RF*=Xm-tjeO7UUk+>mo^FN~e_kX|)H_7h9gBxcz zn%!_<=KCv0pInP1gN-ujD``Hd~z!Kz3x*TKO*$WOtfP6}qW6ZN`^gaUc z2VIVlSAKs){9cV@pGb>mvQPZ`xMIdX@|%W-f0{jMcKLvPR{4kWoA`&s4T+n-M-1&# zX1KBS9v<9CdeQ9a1N*GvhKIz>cMp(#;?JV~*N-v7O^o00;KtI2X4e(&ZTQtR#@@0Q^ChW8@WiASWM4^BY}`(T~bNE_vHu<%G7<_Lafs+CZ*0 z^sjP8A+&vG@Hzc`e`4W(l?x7|?Z@w=ZOM9<<_EG*{Cg^5#y@5t9_inr$Mv6njtwIo zSmmF2zlncH+>p4T$Nt}Knc*fJ@H728{}yf-^8>56;U#hN-2-HwNRQkxJW#LD Wt^QlMVXT)}#SI@A@UPy#^8Wzjt8qmD From fe547feb74329804218084883de8edae76591b84 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 09:17:12 -0600 Subject: [PATCH 134/212] Don't keep track of non-burnable materials --- openmc/deplete/atom_number.py | 38 +++--------- openmc/deplete/openmc_wrapper.py | 64 ++++++-------------- tests/unit_tests/test_deplete_atom_number.py | 27 +++------ 3 files changed, 34 insertions(+), 95 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 63c9af8364..f9d85091ae 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -19,8 +19,6 @@ class AtomNumber(object): A dictionary mapping nuclide name as string to index. volume : OrderedDict of int to float Volume of geometry. - n_mat_burn : int - Number of materials to be burned. n_nuc_burn : int Number of nuclides to be burned. @@ -33,8 +31,6 @@ class AtomNumber(object): volume : numpy.array Volume of geometry indexed by mat_to_ind. If a volume is not found, it defaults to 1 so that reading density still works correctly. - n_mat_burn : int - Number of materials to be burned. n_nuc_burn : int Number of nuclides to be burned. n_mat : int @@ -45,30 +41,26 @@ class AtomNumber(object): Array storing total atoms indexed by the above dictionaries. burn_nuc_list : list of str A list of all nuclide material names. Used for sorting the simulation. - burn_mat_list : list of str - A list of all burning material names. Used for sorting the simulation. - """ - def __init__(self, mat_to_ind, nuc_to_ind, volume, n_mat_burn, n_nuc_burn): + """ + def __init__(self, mat_to_ind, nuc_to_ind, volume, n_nuc_burn): self.mat_to_ind = mat_to_ind self.nuc_to_ind = nuc_to_ind - self.volume = np.ones(self.n_mat) + self.volume = np.ones(len(mat_to_ind)) for mat in volume: - if str(mat) in self.mat_to_ind: - ind = self.mat_to_ind[str(mat)] + if mat in self.mat_to_ind: + ind = self.mat_to_ind[mat] self.volume[ind] = volume[mat] - self.n_mat_burn = n_mat_burn self.n_nuc_burn = n_nuc_burn self.number = np.zeros((self.n_mat, self.n_nuc)) # For performance, create storage for burn_nuc_list, burn_mat_list self._burn_nuc_list = None - self._burn_mat_list = None def __getitem__(self, pos): """Retrieves total atom number from AtomNumber. @@ -175,7 +167,7 @@ class AtomNumber(object): if isinstance(mat, str): mat = self.mat_to_ind[mat] - return self[mat, 0:self.n_nuc_burn] + return self[mat, :self.n_nuc_burn] def set_mat_slice(self, mat, val): """Sets atom quantity indexed by mats for all burned nuclides @@ -191,7 +183,7 @@ class AtomNumber(object): if isinstance(mat, str): mat = self.mat_to_ind[mat] - self[mat, 0:self.n_nuc_burn] = val + self[mat, :self.n_nuc_burn] = val @property def n_mat(self): @@ -218,19 +210,3 @@ class AtomNumber(object): self._burn_nuc_list[ind] = nuc return self._burn_nuc_list - - @property - def burn_mat_list(self): - """burn_mat_list : list of str - A list of all burning material names. Used for sorting the simulation. - """ - - if self._burn_mat_list is None: - self._burn_mat_list = [None] * self.n_mat_burn - - for mat in self.mat_to_ind: - ind = self.mat_to_ind[mat] - if ind < self.n_mat_burn: - self._burn_mat_list[ind] = mat - - return self._burn_mat_list diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index e5eaf52dc0..b25afb79b3 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -121,9 +121,9 @@ class OpenMCOperator(Operator): The depletion chain information necessary to form matrices and tallies. reaction_rates : openmc.deplete.ReactionRates Reaction rates from the last operator step. - burn_mat_to_id : OrderedDict of str to int + burn_mat_to_ind : OrderedDict of str to int Dictionary mapping material ID (as a string) to an index in reaction_rates. - burn_nuc_to_id : OrderedDict of str to int + burn_nuc_to_ind : OrderedDict of str to int Dictionary mapping nuclide name (as a string) to an index in reaction_rates. n_nuc : int @@ -148,18 +148,16 @@ class OpenMCOperator(Operator): # Clear out OpenMC, create task lists, distribute if comm.rank == 0: openmc.reset_auto_ids() - mat_burn_list, mat_not_burn_list, volume, self.mat_tally_ind, \ + mat_burn_list, volume, self.mat_tally_ind, \ nuc_dict = self.extract_mat_ids() else: # Dummy variables mat_burn_list = None - mat_not_burn_list = None volume = None nuc_dict = None self.mat_tally_ind = None mat_burn = comm.scatter(mat_burn_list) - mat_not_burn = comm.scatter(mat_not_burn_list) nuc_dict = comm.bcast(nuc_dict) volume = comm.bcast(volume) self.mat_tally_ind = comm.bcast(self.mat_tally_ind) @@ -168,7 +166,7 @@ class OpenMCOperator(Operator): self.load_participating() # Extract number densities from the geometry - self.extract_number(mat_burn, mat_not_burn, volume, nuc_dict) + self.extract_number(mat_burn, volume, nuc_dict) # Create reaction rates array index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} @@ -239,9 +237,7 @@ class OpenMCOperator(Operator): """ mat_burn = set() - mat_not_burn = set() nuc_set = set() - volume = OrderedDict() # Iterate once through the geometry to get dictionaries @@ -254,19 +250,14 @@ class OpenMCOperator(Operator): raise RuntimeError("Volume not specified for depletable " "material with ID={}.".format(mat.id)) volume[str(mat.id)] = mat.volume - else: - mat_not_burn.add(str(mat.id)) # Sort the sets mat_burn = sorted(mat_burn, key=int) - mat_not_burn = sorted(mat_not_burn, key=int) nuc_set = sorted(nuc_set) # Construct a global nuclide dictionary, burned first nuc_dict = copy.deepcopy(self.chain.nuclide_dict) - i = len(nuc_dict) - for nuc in nuc_set: if nuc not in nuc_dict: nuc_dict[nuc] = i @@ -274,47 +265,35 @@ class OpenMCOperator(Operator): # Decompose geometry mat_burn_lists = _chunks(mat_burn, comm.size) - mat_not_burn_lists = _chunks(mat_not_burn, comm.size) mat_tally_ind = OrderedDict() - for i, mat in enumerate(mat_burn): mat_tally_ind[mat] = i - return mat_burn_lists, mat_not_burn_lists, volume, mat_tally_ind, nuc_dict + return mat_burn_lists, volume, mat_tally_ind, nuc_dict - def extract_number(self, mat_burn, mat_not_burn, volume, nuc_dict): + def extract_number(self, mat_burn, volume, nuc_dict): """Construct self.number read from geometry Parameters ---------- mat_burn : list of int Materials to be burned managed by this thread. - mat_not_burn - Materials not to be burned managed by this thread. volume : OrderedDict of str to float Volumes for the above materials. nuc_dict : OrderedDict of str to int Nuclides to be used in the simulation. + """ - # Same with materials - mat_dict = OrderedDict() self.burn_mat_to_ind = OrderedDict() - i = 0 - for mat in mat_burn: - mat_dict[mat] = i + for i, mat in enumerate(mat_burn): self.burn_mat_to_ind[mat] = i - i += 1 - for mat in mat_not_burn: - mat_dict[mat] = i - i += 1 - - n_mat_burn = len(mat_burn) n_nuc_burn = len(self.chain) - self.number = AtomNumber(mat_dict, nuc_dict, volume, n_mat_burn, n_nuc_burn) + self.number = AtomNumber(self.burn_mat_to_ind, nuc_dict, volume, + n_nuc_burn) if self.settings.dilute_initial != 0.0: for nuc in self.burn_nuc_to_ind: @@ -323,7 +302,7 @@ class OpenMCOperator(Operator): # Now extract the number densities and store for mat in self.geometry.get_all_materials().values(): - if str(mat.id) in mat_dict: + if str(mat.id) in self.burn_mat_to_ind: self.set_number_from_mat(mat) def set_number_from_mat(self, mat): @@ -397,9 +376,6 @@ class OpenMCOperator(Operator): number_i = comm.bcast(self.number, root=rank) for mat in number_i.mat_to_ind: - if number_i.mat_to_ind[mat] >= number_i.n_mat_burn: - continue - nuclides = [] densities = [] for nuc in number_i.nuc_to_ind: @@ -507,12 +483,10 @@ class OpenMCOperator(Operator): Returns ------- list of numpy.array - A list of np.arrays containing total atoms of each cell. + A list of arrays containing total atoms of each material + """ - - total_density = [self.number.get_mat_slice(i) for i in range(self.number.n_mat_burn)] - - return total_density + return list(self.number.get_mat_slice(np.s_[:])) def set_density(self, total_density): """Sets density. @@ -522,12 +496,12 @@ class OpenMCOperator(Operator): Parameters ---------- - total_density : list of numpy.array + total_density : list of numpy.ndarray Total atoms. - """ + """ # Fill in values - for i in range(self.number.n_mat_burn): + for i in range(self.number.n_mat): self.number.set_mat_slice(i, total_density[i]) def unpack_tallies_and_normalize(self): @@ -581,7 +555,7 @@ class OpenMCOperator(Operator): break # Extract results - for i, mat in enumerate(self.number.burn_mat_list): + for i, mat in enumerate(self.burn_mat_to_ind): # Get tally index slab = materials.index(mat) @@ -686,7 +660,7 @@ class OpenMCOperator(Operator): """ nuc_list = self.number.burn_nuc_list - burn_list = self.number.burn_mat_list + burn_list = list(self.burn_mat_to_ind) volume = {} for i, mat in enumerate(burn_list): diff --git a/tests/unit_tests/test_deplete_atom_number.py b/tests/unit_tests/test_deplete_atom_number.py index e3eb22aa55..887e9af1bc 100644 --- a/tests/unit_tests/test_deplete_atom_number.py +++ b/tests/unit_tests/test_deplete_atom_number.py @@ -7,11 +7,11 @@ from openmc.deplete import atom_number def test_indexing(): """Tests the __getitem__ and __setitem__ routines simultaneously.""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} + mat_to_ind = {"10000" : 0, "10001" : 1} nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) number["10000", "U238"] = 1.0 number["10001", "U238"] = 2.0 @@ -42,7 +42,7 @@ def test_n_mat(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) assert number.n_mat == 2 @@ -53,7 +53,7 @@ def test_n_nuc(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) assert number.n_nuc == 3 @@ -64,22 +64,11 @@ def test_burn_nuc_list(): nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) assert number.burn_nuc_list == ["U238", "U235"] -def test_burn_mat_list(): - """Test the list of burned nuclides property""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) - - assert number.burn_mat_list == ["10000", "10001"] - - def test_density_indexing(): """Tests the get and set_atom_density routines simultaneously.""" @@ -87,7 +76,7 @@ def test_density_indexing(): nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) number.set_atom_density("10000", "U238", 1.0) number.set_atom_density("10001", "U238", 2.0) @@ -144,7 +133,7 @@ def test_get_mat_slice(): nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) @@ -164,7 +153,7 @@ def test_set_mat_slice(): nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2, 2) + number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) number.set_mat_slice(0, [1.0, 2.0]) From 2cd9aecf21628cdda83d5fd5c9606c21ccaafb73 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 10:15:48 -0600 Subject: [PATCH 135/212] Get rid of Operator.mat_tally_ind --- openmc/deplete/openmc_wrapper.py | 42 +++++++++++--------------------- openmc/deplete/results.py | 17 ++++++------- 2 files changed, 22 insertions(+), 37 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index b25afb79b3..7cdfbd4d8b 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -5,6 +5,7 @@ This module implements the depletion -> OpenMC linkage. import copy from collections import OrderedDict +from itertools import chain import os import random import sys @@ -126,10 +127,8 @@ class OpenMCOperator(Operator): burn_nuc_to_ind : OrderedDict of str to int Dictionary mapping nuclide name (as a string) to an index in reaction_rates. - n_nuc : int - Number of nuclides considered in the decay chain. - mat_tally_ind : OrderedDict of str to int - Dictionary mapping material ID to index in tally. + burnable_mats : list of str + All burnable material IDs """ def __init__(self, geometry, settings): @@ -138,7 +137,6 @@ class OpenMCOperator(Operator): self.geometry = geometry self.number = None self.participating_nuclides = None - self.reaction_rates = None self.burn_mat_to_ind = OrderedDict() self.burn_nuc_to_ind = None @@ -148,19 +146,18 @@ class OpenMCOperator(Operator): # Clear out OpenMC, create task lists, distribute if comm.rank == 0: openmc.reset_auto_ids() - mat_burn_list, volume, self.mat_tally_ind, \ - nuc_dict = self.extract_mat_ids() + mat_burn_list, volume, nuc_dict = self.extract_mat_ids() else: # Dummy variables mat_burn_list = None volume = None nuc_dict = None - self.mat_tally_ind = None - mat_burn = comm.scatter(mat_burn_list) + mat_burn_list = comm.bcast(mat_burn_list) nuc_dict = comm.bcast(nuc_dict) volume = comm.bcast(volume) - self.mat_tally_ind = comm.bcast(self.mat_tally_ind) + mat_burn = mat_burn_list[comm.rank] + self.burnable_mats = list(chain(*mat_burn_list)) # Load participating nuclides self.load_participating() @@ -230,8 +227,6 @@ class OpenMCOperator(Operator): List of non-burnable materials indexed by rank. volume : OrderedDict of str to float Volume of each cell - mat_tally_ind : OrderedDict of str to int - Dictionary mapping material ID to index in tally. nuc_dict : OrderedDict of str to int Nuclides in order of how they'll appear in the simulation. """ @@ -266,11 +261,7 @@ class OpenMCOperator(Operator): # Decompose geometry mat_burn_lists = _chunks(mat_burn, comm.size) - mat_tally_ind = OrderedDict() - for i, mat in enumerate(mat_burn): - mat_tally_ind[mat] = i - - return mat_burn_lists, volume, mat_tally_ind, nuc_dict + return mat_burn_lists, volume, nuc_dict def extract_number(self, mat_burn, volume, nuc_dict): """Construct self.number read from geometry @@ -463,7 +454,7 @@ class OpenMCOperator(Operator): """ # Create tallies for depleting regions materials = [openmc.capi.materials[int(i)] - for i in self.mat_tally_ind] + for i in self.burnable_mats] mat_filter = openmc.capi.MaterialFilter(materials, 1) # Set up a tally that has a material filter covering each depletable @@ -524,7 +515,7 @@ class OpenMCOperator(Operator): k_combined = openmc.capi.keff()[0] # Extract tally bins - materials = list(self.mat_tally_ind.keys()) + materials = self.burnable_mats nuclides = openmc.capi.tallies[1].nuclides # Form fast map @@ -639,11 +630,6 @@ class OpenMCOperator(Operator): self.burn_nuc_to_ind[name] = nuc_ind nuc_ind += 1 - @property - def n_nuc(self): - """Number of nuclides considered in the decay chain.""" - return len(self.chain) - def get_results_info(self): """Returns volume list, cell lists, and nuc lists. @@ -655,10 +641,10 @@ class OpenMCOperator(Operator): A list of all nuclide names. Used for sorting the simulation. burn_list : list of int A list of all cell IDs to be burned. Used for sorting the simulation. - full_burn_dict : OrderedDict of str to int - Maps cell name to index in global geometry. - """ + full_burn_list : list + List of all burnable material IDs + """ nuc_list = self.number.burn_nuc_list burn_list = list(self.burn_mat_to_ind) @@ -670,7 +656,7 @@ class OpenMCOperator(Operator): volume_list = comm.allgather(volume) volume = {k: v for d in volume_list for k, v in d.items()} - return volume, nuc_list, burn_list, self.mat_tally_ind + return volume, nuc_list, burn_list, self.burnable_mats def density_to_mat(dens_dict): diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 539ce5dd67..f7daca5b2e 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -58,7 +58,7 @@ class Results(object): self.data = None - def allocate(self, volume, nuc_list, burn_list, full_burn_dict, stages): + def allocate(self, volume, nuc_list, burn_list, full_burn_list, stages): """Allocates memory of Results. Parameters @@ -69,16 +69,16 @@ class Results(object): A list of all nuclide names. Used for sorting the simulation. burn_list : list of int A list of all mat IDs to be burned. Used for sorting the simulation. - full_burn_dict : dict of str to int - Map of material name to id in global geometry. + full_burn_list : list of str + List of all burnable material IDs stages : int Number of stages in simulation. - """ + """ self.volume = copy.deepcopy(volume) self.nuc_to_ind = OrderedDict() self.mat_to_ind = OrderedDict() - self.mat_to_hdf5_ind = copy.deepcopy(full_burn_dict) + self.mat_to_hdf5_ind = {mat: i for i, mat in enumerate(full_burn_list)} for i, mat in enumerate(burn_list): self.mat_to_ind[mat] = i @@ -177,10 +177,9 @@ class Results(object): handle.create_dataset("version", data=RESULTS_VERSION) - mat_int = sorted([int(mat) for mat in self.mat_to_hdf5_ind]) - mat_list = [str(mat) for mat in mat_int] - nuc_list = sorted(self.nuc_to_ind.keys()) - rxn_list = sorted(self.rates[0].index_rx.keys()) + mat_list = sorted(self.mat_to_hdf5_ind, key=int) + nuc_list = sorted(self.nuc_to_ind) + rxn_list = sorted(self.rates[0].index_rx) n_mats = self.n_hdf5_mats n_nuc_number = len(nuc_list) From 4e21e398c83f0997fc20b7c4a08952cfc73b482b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 10:19:02 -0600 Subject: [PATCH 136/212] Move density_to_mat to example_geometry.py --- openmc/deplete/openmc_wrapper.py | 21 --------------------- scripts/example_geometry.py | 23 ++++++++++++++++++++++- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 7cdfbd4d8b..c8a3bcca99 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -657,24 +657,3 @@ class OpenMCOperator(Operator): volume = {k: v for d in volume_list for k, v in d.items()} return volume, nuc_list, burn_list, self.burnable_mats - - -def density_to_mat(dens_dict): - """Generates an OpenMC material from a cell ID and self.number_density. - - Parameters - ---------- - m_id : int - Cell ID. - Returns - ------- - openmc.Material - The OpenMC material filled with nuclides. - """ - - mat = openmc.Material() - for key in dens_dict: - mat.add_nuclide(key, 1.0e-24*dens_dict[key]) - mat.set_density('sum') - - return mat diff --git a/scripts/example_geometry.py b/scripts/example_geometry.py index 09ce0576f1..ca10c1f725 100644 --- a/scripts/example_geometry.py +++ b/scripts/example_geometry.py @@ -9,7 +9,28 @@ import math import numpy as np import openmc -from openmc.deplete import density_to_mat + + +def density_to_mat(dens_dict): + """Generates an OpenMC material from a cell ID and self.number_density. + + Parameters + ---------- + dens_dict : dict + Dictionary mapping nuclide names to densities + + Returns + ------- + openmc.Material + The OpenMC material filled with nuclides. + + """ + mat = openmc.Material() + for key in dens_dict: + mat.add_nuclide(key, 1.0e-24*dens_dict[key]) + mat.set_density('sum') + + return mat def generate_initial_number_density(): From ea335e06961a94c6b680462e24224b998920f5dc Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 10:24:10 -0600 Subject: [PATCH 137/212] Change OPENDEPLETE_CHAIN -> OPENMC_DEPLETE_CHAIN --- openmc/deplete/abc.py | 6 +++--- openmc/deplete/chain.py | 4 ++-- openmc/deplete/openmc_wrapper.py | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 5441829b40..e8f65f8871 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -23,8 +23,8 @@ class Settings(object): output_dir : pathlib.Path Path to output directory to save results. chain_file : str - Path to the depletion chain xml file. Defaults to the - :envvar:`OPENDEPLETE_CHAIN` environment variable if it exists. + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. dilute_initial : float Initial atom density to add for nuclides that are zero in initial condition to ensure they exist in the decay chain. Only done for @@ -37,7 +37,7 @@ class Settings(object): """ def __init__(self): try: - self.chain_file = os.environ["OPENDEPLETE_CHAIN"] + self.chain_file = os.environ["OPENMC_DEPLETE_CHAIN"] except KeyError: self.chain_file = None self.dt_vec = None diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 2af64e172a..2d2e71a776 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -332,9 +332,9 @@ class Chain(object): root = ET.parse(filename) except Exception: if filename is None: - print("No chain specified, either manually or in environment variable OPENDEPLETE_CHAIN.") + print("No chain specified, either manually or in environment variable OPENMC_DEPLETE_CHAIN.") else: - print('Decay chain "', filename, '" is invalid.') + print('Decay chain "{}" is invalid.'.format(filename)) raise for i, nuclide_elem in enumerate(root.findall('nuclide_table')): diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index c8a3bcca99..a01949a911 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -51,8 +51,8 @@ class OpenMCSettings(Settings): output_dir : pathlib.Path Path to output directory to save results. chain_file : str - Path to the depletion chain xml file. Defaults to the - :envvar:`OPENDEPLETE_CHAIN` environment variable if it exists. + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. dilute_initial : float Initial atom density to add for nuclides that are zero in initial condition to ensure they exist in the decay chain. Only done for From 78e1afb0ffb6e07c32714967ea0001e120303b28 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 13:10:28 -0600 Subject: [PATCH 138/212] Rename participating_nuclides -> nuclides_with_data --- openmc/deplete/atom_number.py | 14 ++--- openmc/deplete/chain.py | 7 ++- openmc/deplete/openmc_wrapper.py | 103 +++++++++++++++---------------- 3 files changed, 60 insertions(+), 64 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index f9d85091ae..fc9cb8433b 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -96,9 +96,9 @@ class AtomNumber(object): These indexes can be strings (which get converted to integers via the dictionaries), integers used directly, or slices. val : float - The value to set the array to. - """ + The value [atom] to set the array to. + """ mat, nuc = pos if isinstance(mat, str): mat = self.mat_to_ind[mat] @@ -119,10 +119,10 @@ class AtomNumber(object): Returns ------- - numpy.array - The density indexed. - """ + numpy.ndarray + Density in [atom/cm^3] + """ if isinstance(mat, str): mat = self.mat_to_ind[mat] if isinstance(nuc, str): @@ -140,9 +140,9 @@ class AtomNumber(object): nuc : str, int or slice Nuclide index. val : numpy.array - Array of values to set. - """ + Array of densities to set in [atom/cm^3] + """ if isinstance(mat, str): mat = self.mat_to_ind[mat] if isinstance(nuc, str): diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 2d2e71a776..ec8d79f819 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -332,10 +332,11 @@ class Chain(object): root = ET.parse(filename) except Exception: if filename is None: - print("No chain specified, either manually or in environment variable OPENMC_DEPLETE_CHAIN.") + msg = ("No chain specified, either manually or in environment " + "variable OPENMC_DEPLETE_CHAIN.") else: - print('Decay chain "{}" is invalid.'.format(filename)) - raise + msg = 'Decay chain "{}" is invalid.'.format(filename) + raise IOError(msg) for i, nuclide_elem in enumerate(root.findall('nuclide_table')): nuc = Nuclide.from_xml(nuclide_elem) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index a01949a911..7120926bcf 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -116,7 +116,7 @@ class OpenMCOperator(Operator): The OpenMC geometry object. number : openmc.deplete.AtomNumber Total number of atoms in simulation. - participating_nuclides : set of str + nuclides_with_data : set of str A set listing all unique nuclides available from cross_sections.xml. chain : openmc.deplete.Chain The depletion chain information necessary to form matrices and tallies. @@ -126,7 +126,8 @@ class OpenMCOperator(Operator): Dictionary mapping material ID (as a string) to an index in reaction_rates. burn_nuc_to_ind : OrderedDict of str to int Dictionary mapping nuclide name (as a string) to an index in - reaction_rates. + reaction_rates. Consists of all nuclides with neutron data and appearing + in the depletion chain. burnable_mats : list of str All burnable material IDs @@ -136,7 +137,6 @@ class OpenMCOperator(Operator): self.geometry = geometry self.number = None - self.participating_nuclides = None self.burn_mat_to_ind = OrderedDict() self.burn_nuc_to_ind = None @@ -146,7 +146,7 @@ class OpenMCOperator(Operator): # Clear out OpenMC, create task lists, distribute if comm.rank == 0: openmc.reset_auto_ids() - mat_burn_list, volume, nuc_dict = self.extract_mat_ids() + mat_burn_list, volume, nuc_dict = self._extract_mat_ids() else: # Dummy variables mat_burn_list = None @@ -160,10 +160,10 @@ class OpenMCOperator(Operator): self.burnable_mats = list(chain(*mat_burn_list)) # Load participating nuclides - self.load_participating() + self._load_participating() # Extract number densities from the geometry - self.extract_number(mat_burn, volume, nuc_dict) + self._extract_number(mat_burn, volume, nuc_dict) # Create reaction rates array index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} @@ -190,7 +190,7 @@ class OpenMCOperator(Operator): openmc.reset_auto_ids() # Update status - self.set_density(vec) + self._set_density(vec) time_start = time.time() @@ -205,7 +205,7 @@ class OpenMCOperator(Operator): time_openmc = time.time() # Extract results - op_result = self.unpack_tallies_and_normalize() + op_result = self._unpack_tallies_and_normalize() if comm.rank == 0: time_unpack = time.time() @@ -216,7 +216,7 @@ class OpenMCOperator(Operator): return copy.deepcopy(op_result) - def extract_mat_ids(self): + def _extract_mat_ids(self): """Extracts materials and assigns them to processes. Returns @@ -229,15 +229,15 @@ class OpenMCOperator(Operator): Volume of each cell nuc_dict : OrderedDict of str to int Nuclides in order of how they'll appear in the simulation. - """ + """ mat_burn = set() nuc_set = set() volume = OrderedDict() # Iterate once through the geometry to get dictionaries for mat in self.geometry.get_all_materials().values(): - for nuclide in mat.get_nuclide_densities(): + for nuclide in mat.get_nuclides(): nuc_set.add(nuclide) if mat.depletable: mat_burn.add(str(mat.id)) @@ -263,7 +263,7 @@ class OpenMCOperator(Operator): return mat_burn_lists, volume, nuc_dict - def extract_number(self, mat_burn, volume, nuc_dict): + def _extract_number(self, mat_burn, volume, nuc_dict): """Construct self.number read from geometry Parameters @@ -281,10 +281,8 @@ class OpenMCOperator(Operator): for i, mat in enumerate(mat_burn): self.burn_mat_to_ind[mat] = i - n_nuc_burn = len(self.chain) - self.number = AtomNumber(self.burn_mat_to_ind, nuc_dict, volume, - n_nuc_burn) + len(self.chain)) if self.settings.dilute_initial != 0.0: for nuc in self.burn_nuc_to_ind: @@ -294,23 +292,22 @@ class OpenMCOperator(Operator): # Now extract the number densities and store for mat in self.geometry.get_all_materials().values(): if str(mat.id) in self.burn_mat_to_ind: - self.set_number_from_mat(mat) + self._set_number_from_mat(mat) - def set_number_from_mat(self, mat): + def _set_number_from_mat(self, mat): """Extracts material and number densities from openmc.Material Parameters ---------- - mat : openmc.Materials + mat : openmc.Material The material to read from - """ + """ mat_id = str(mat.id) mat_ind = self.number.mat_to_ind[mat_id] - nuc_dens = mat.get_nuclide_atom_densities() - for nuclide in nuc_dens: - number = nuc_dens[nuclide][1] * 1.0e24 + for nuclide, density in mat.get_nuclide_atom_densities().values(): + number = density * 1.0e24 self.number.set_atom_density(mat_id, nuclide, number) def form_matrix(self, y, mat): @@ -344,17 +341,17 @@ class OpenMCOperator(Operator): if comm.rank == 0: self.geometry.export_to_xml() self.settings.settings.export_to_xml() - self.generate_materials_xml() + self._generate_materials_xml() # Initialize OpenMC library comm.barrier() openmc.capi.init(comm) # Generate tallies in memory - self.generate_tallies() + self._generate_tallies() # Return number density vector - return self.total_density_list() + return list(self.number.get_mat_slice(np.s_[:])) def finalize(self): """Finalize a depletion simulation and release resources.""" @@ -370,7 +367,7 @@ class OpenMCOperator(Operator): nuclides = [] densities = [] for nuc in number_i.nuc_to_ind: - if nuc in self.participating_nuclides: + if nuc in self.nuclides_with_data: val = 1.0e-24 * number_i.get_atom_density(mat, nuc) # If nuclide is zero, do not add to the problem. @@ -395,14 +392,14 @@ class OpenMCOperator(Operator): mat_internal = openmc.capi.materials[int(mat)] mat_internal.set_densities(nuclides, densities) - def generate_materials_xml(self): + def _generate_materials_xml(self): """Creates materials.xml from self.number. Due to uncertainty with how MPI interacts with OpenMC API, this constructs the XML manually. The long term goal is to do this through direct memory writing. - """ + """ materials = openmc.Materials(self.geometry.get_all_materials() .values()) @@ -414,12 +411,26 @@ class OpenMCOperator(Operator): materials.export_to_xml() def _get_tally_nuclides(self): + """Determine nuclides that should be tallied for reaction rates. + + This method returns a list of all nuclides that have neutron data and + are listed in the depletion chain. Technically, we should tally nuclides + that may not appear in the depletion chain because we still need to get + the fission reaction rate for these nuclides in order to normalize + power, but that is left as a future exercise. + + Returns + ------- + list of str + Tally nuclides + + """ nuc_set = set() # Create the set of all nuclides in the decay chain in cells marked for # burning in which the number density is greater than zero. for nuc in self.number.nuc_to_ind: - if nuc in self.participating_nuclides: + if nuc in self.nuclides_with_data: if np.sum(self.number[:, nuc]) > 0.0: nuc_set.add(nuc) @@ -439,12 +450,10 @@ class OpenMCOperator(Operator): nuc_list = None # Store list of tally nuclides on each process - nuc_list = comm.bcast(nuc_list, root=0) - tally_nuclides = [nuc for nuc in nuc_list if nuc in self.chain] + nuc_list = comm.bcast(nuc_list) + return [nuc for nuc in nuc_list if nuc in self.chain] - return tally_nuclides - - def generate_tallies(self): + def _generate_tallies(self): """Generates depletion tallies. Using information from the depletion chain as well as the nuclides @@ -465,21 +474,7 @@ class OpenMCOperator(Operator): tally_dep.scores = self.chain.reactions tally_dep.filters = [mat_filter] - def total_density_list(self): - """Returns a list of total density lists. - - This list is in the exact same order as depletion_matrix_list, so that - matrix exponentiation can be done easily. - - Returns - ------- - list of numpy.array - A list of arrays containing total atoms of each material - - """ - return list(self.number.get_mat_slice(np.s_[:])) - - def set_density(self, total_density): + def _set_density(self, total_density): """Sets density. Sets the density in the exact same order as total_density_list outputs, @@ -495,7 +490,7 @@ class OpenMCOperator(Operator): for i in range(self.number.n_mat): self.number.set_mat_slice(i, total_density[i]) - def unpack_tallies_and_normalize(self): + def _unpack_tallies_and_normalize(self): """Unpack tallies from OpenMC and return an operator result This method uses OpenMC's C API bindings to determine the k-effective @@ -587,7 +582,7 @@ class OpenMCOperator(Operator): return OperatorResult(k_combined, rates) - def load_participating(self): + def _load_participating(self): """Loads a cross_sections.xml file to find participating nuclides. This allows for nuclides that are important in the decay chain but not @@ -602,7 +597,7 @@ class OpenMCOperator(Operator): except KeyError: filename = None - self.participating_nuclides = set() + self.nuclides_with_data = set() try: tree = ET.parse(filename) @@ -624,8 +619,8 @@ class OpenMCOperator(Operator): for name in mats.split(): # Make a burn list of the union of nuclides in cross_sections.xml # and nuclides in depletion chain. - if name not in self.participating_nuclides: - self.participating_nuclides.add(name) + if name not in self.nuclides_with_data: + self.nuclides_with_data.add(name) if name in self.chain: self.burn_nuc_to_ind[name] = nuc_ind nuc_ind += 1 From 6832071b4cf8a5f1b01d20079a902b83abac7e4c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 13:35:51 -0600 Subject: [PATCH 139/212] Move set_density method to AtomNumber --- openmc/deplete/atom_number.py | 69 +++++++++++++++++++------------- openmc/deplete/openmc_wrapper.py | 18 +-------- 2 files changed, 43 insertions(+), 44 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index fc9cb8433b..f1b0155d73 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -107,6 +107,32 @@ class AtomNumber(object): self.number[mat, nuc] = val + @property + def n_mat(self): + """Number of materials.""" + return len(self.mat_to_ind) + + @property + def n_nuc(self): + """Number of nuclides.""" + return len(self.nuc_to_ind) + + @property + def burn_nuc_list(self): + """burn_nuc_list : list of str + A list of all nuclide material names. Used for sorting the simulation. + """ + + if self._burn_nuc_list is None: + self._burn_nuc_list = [None] * self.n_nuc_burn + + for nuc in self.nuc_to_ind: + ind = self.nuc_to_ind[nuc] + if ind < self.n_nuc_burn: + self._burn_nuc_list[ind] = nuc + + return self._burn_nuc_list + def get_atom_density(self, mat, nuc): """Accesses atom density instead of total number. @@ -160,10 +186,10 @@ class AtomNumber(object): Returns ------- - numpy.array - The slice requested. - """ + numpy.ndarray + The slice requested in [atom]. + """ if isinstance(mat, str): mat = self.mat_to_ind[mat] @@ -177,36 +203,25 @@ class AtomNumber(object): mat : str, int or slice Material index. val : numpy.array - The slice to set. - """ + The slice to set in [atom] + """ if isinstance(mat, str): mat = self.mat_to_ind[mat] self[mat, :self.n_nuc_burn] = val - @property - def n_mat(self): - """Number of materials.""" - return len(self.mat_to_ind) + def set_density(self, total_density): + """Sets density. - @property - def n_nuc(self): - """Number of nuclides.""" - return len(self.nuc_to_ind) + Sets the density in the exact same order as total_density_list outputs, + allowing for internal consistency + + Parameters + ---------- + total_density : list of numpy.ndarray + Total atoms. - @property - def burn_nuc_list(self): - """burn_nuc_list : list of str - A list of all nuclide material names. Used for sorting the simulation. """ - - if self._burn_nuc_list is None: - self._burn_nuc_list = [None] * self.n_nuc_burn - - for nuc in self.nuc_to_ind: - ind = self.nuc_to_ind[nuc] - if ind < self.n_nuc_burn: - self._burn_nuc_list[ind] = nuc - - return self._burn_nuc_list + for i in range(self.n_mat): + self.set_mat_slice(i, total_density[i]) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 7120926bcf..43a171afc5 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -190,7 +190,7 @@ class OpenMCOperator(Operator): openmc.reset_auto_ids() # Update status - self._set_density(vec) + self.number.set_density(vec) time_start = time.time() @@ -474,22 +474,6 @@ class OpenMCOperator(Operator): tally_dep.scores = self.chain.reactions tally_dep.filters = [mat_filter] - def _set_density(self, total_density): - """Sets density. - - Sets the density in the exact same order as total_density_list outputs, - allowing for internal consistency - - Parameters - ---------- - total_density : list of numpy.ndarray - Total atoms. - - """ - # Fill in values - for i in range(self.number.n_mat): - self.number.set_mat_slice(i, total_density[i]) - def _unpack_tallies_and_normalize(self): """Unpack tallies from OpenMC and return an operator result From 2a1c66913ad0a22c91757bf231e0023825f01110 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 13:47:49 -0600 Subject: [PATCH 140/212] Don't use hard-wired IDs for MaterialFilter and Tally --- openmc/deplete/openmc_wrapper.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 43a171afc5..42bd0e600e 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -196,7 +196,7 @@ class OpenMCOperator(Operator): # Update material compositions and tally nuclides self._update_materials() - openmc.capi.tallies[1].nuclides = self._get_tally_nuclides() + self._tally.nuclides = self._get_tally_nuclides() # Run OpenMC openmc.capi.reset() @@ -464,15 +464,15 @@ class OpenMCOperator(Operator): # Create tallies for depleting regions materials = [openmc.capi.materials[int(i)] for i in self.burnable_mats] - mat_filter = openmc.capi.MaterialFilter(materials, 1) + mat_filter = openmc.capi.MaterialFilter(materials) # Set up a tally that has a material filter covering each depletable # material and scores corresponding to all reactions that cause # transmutation. The nuclides for the tally are set later when eval() is # called. - tally_dep = openmc.capi.Tally(1) - tally_dep.scores = self.chain.reactions - tally_dep.filters = [mat_filter] + self._tally = openmc.capi.Tally() + self._tally.scores = self.chain.reactions + self._tally.filters = [mat_filter] def _unpack_tallies_and_normalize(self): """Unpack tallies from OpenMC and return an operator result @@ -495,7 +495,7 @@ class OpenMCOperator(Operator): # Extract tally bins materials = self.burnable_mats - nuclides = openmc.capi.tallies[1].nuclides + nuclides = self._tally.nuclides # Form fast map nuc_ind = [rates.index_nuc[nuc] for nuc in nuclides] @@ -530,7 +530,7 @@ class OpenMCOperator(Operator): slab = materials.index(mat) # Get material results hyperslab - results = openmc.capi.tallies[1].results[slab, :, 1] + results = self._tally.results[slab, :, 1] # Zero out reaction rates and nuclide numbers rates_expanded[:] = 0.0 From 945675aaaa5d27b7347c81fc17c97a945487f1f9 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 14:14:56 -0600 Subject: [PATCH 141/212] Simplification of OpenMCOperator.__init__ --- openmc/deplete/atom_number.py | 2 +- openmc/deplete/openmc_wrapper.py | 79 ++++++++++++-------------------- 2 files changed, 30 insertions(+), 51 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index f1b0155d73..3ad4968a82 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -18,7 +18,7 @@ class AtomNumber(object): nuc_to_ind : OrderedDict of str to int A dictionary mapping nuclide name as string to index. volume : OrderedDict of int to float - Volume of geometry. + Volume of each material in [cm^3] n_nuc_burn : int Number of nuclides to be burned. diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 42bd0e600e..f3afedb298 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -30,15 +30,14 @@ from .chain import Chain from .reaction_rates import ReactionRates -def _chunks(items, n): - min_size, extra = divmod(len(items), n) +def _distribute(items): + min_size, extra = divmod(len(items), comm.size) j = 0 - chunk_list = [] - for i in range(n): + for i in range(comm.size): chunk_size = min_size + int(i < extra) - chunk_list.append(items[j:j + chunk_size]) + if comm.rank == i: + return items[j:j + chunk_size] j += chunk_size - return chunk_list class OpenMCSettings(Settings): @@ -134,36 +133,21 @@ class OpenMCOperator(Operator): """ def __init__(self, geometry, settings): super().__init__(settings) - self.geometry = geometry - self.number = None - self.burn_mat_to_ind = OrderedDict() - self.burn_nuc_to_ind = None # Read depletion chain self.chain = Chain.from_xml(settings.chain_file) # Clear out OpenMC, create task lists, distribute - if comm.rank == 0: - openmc.reset_auto_ids() - mat_burn_list, volume, nuc_dict = self._extract_mat_ids() - else: - # Dummy variables - mat_burn_list = None - volume = None - nuc_dict = None + openmc.reset_auto_ids() + self.burnable_mats, volume, nuc_dict = self._get_burnable_mats() + local_mats = _distribute(self.burnable_mats) - mat_burn_list = comm.bcast(mat_burn_list) - nuc_dict = comm.bcast(nuc_dict) - volume = comm.bcast(volume) - mat_burn = mat_burn_list[comm.rank] - self.burnable_mats = list(chain(*mat_burn_list)) - - # Load participating nuclides + # Determine which nuclides have incident neutron data self._load_participating() # Extract number densities from the geometry - self._extract_number(mat_burn, volume, nuc_dict) + self._extract_number(local_mats, volume, nuc_dict) # Create reaction rates array index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} @@ -216,69 +200,64 @@ class OpenMCOperator(Operator): return copy.deepcopy(op_result) - def _extract_mat_ids(self): - """Extracts materials and assigns them to processes. + def _get_burnable_mats(self): + """Determine depletable materials, volumes, and nuclids Returns ------- - mat_burn_lists : list of list of int - List of burnable materials indexed by rank. - mat_not_burn_lists : list of list of int - List of non-burnable materials indexed by rank. + burnable_mats : list of str + List of burnable material IDs volume : OrderedDict of str to float - Volume of each cell + Volume of each material in [cm^3] nuc_dict : OrderedDict of str to int Nuclides in order of how they'll appear in the simulation. """ - mat_burn = set() - nuc_set = set() + burnable_mats = set() + model_nuclides = set() volume = OrderedDict() # Iterate once through the geometry to get dictionaries for mat in self.geometry.get_all_materials().values(): for nuclide in mat.get_nuclides(): - nuc_set.add(nuclide) + model_nuclides.add(nuclide) if mat.depletable: - mat_burn.add(str(mat.id)) + burnable_mats.add(str(mat.id)) if mat.volume is None: raise RuntimeError("Volume not specified for depletable " "material with ID={}.".format(mat.id)) volume[str(mat.id)] = mat.volume # Sort the sets - mat_burn = sorted(mat_burn, key=int) - nuc_set = sorted(nuc_set) + burnable_mats = sorted(burnable_mats, key=int) + model_nuclides = sorted(model_nuclides) # Construct a global nuclide dictionary, burned first nuc_dict = copy.deepcopy(self.chain.nuclide_dict) i = len(nuc_dict) - for nuc in nuc_set: + for nuc in model_nuclides: if nuc not in nuc_dict: nuc_dict[nuc] = i i += 1 - # Decompose geometry - mat_burn_lists = _chunks(mat_burn, comm.size) + return burnable_mats, volume, nuc_dict - return mat_burn_lists, volume, nuc_dict - - def _extract_number(self, mat_burn, volume, nuc_dict): - """Construct self.number read from geometry + def _extract_number(self, local_mats, volume, nuc_dict): + """Construct AtomNumber using geometry Parameters ---------- - mat_burn : list of int - Materials to be burned managed by this thread. + local_mats : list of str + Material IDs to be managed by this process volume : OrderedDict of str to float - Volumes for the above materials. + Volumes for the above materials in [cm^3] nuc_dict : OrderedDict of str to int Nuclides to be used in the simulation. """ # Same with materials self.burn_mat_to_ind = OrderedDict() - for i, mat in enumerate(mat_burn): + for i, mat in enumerate(local_mats): self.burn_mat_to_ind[mat] = i self.number = AtomNumber(self.burn_mat_to_ind, nuc_dict, volume, From 65061bdadcb04904edb3775fb837bc1037cfc8bf Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 14:24:48 -0600 Subject: [PATCH 142/212] Change burn_nuc_to_ind to _burnable_nucs --- openmc/deplete/openmc_wrapper.py | 28 +++++++++++----------------- openmc/deplete/reaction_rates.py | 10 +++++----- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index f3afedb298..3c3b974c90 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -123,10 +123,6 @@ class OpenMCOperator(Operator): Reaction rates from the last operator step. burn_mat_to_ind : OrderedDict of str to int Dictionary mapping material ID (as a string) to an index in reaction_rates. - burn_nuc_to_ind : OrderedDict of str to int - Dictionary mapping nuclide name (as a string) to an index in - reaction_rates. Consists of all nuclides with neutron data and appearing - in the depletion chain. burnable_mats : list of str All burnable material IDs @@ -144,7 +140,9 @@ class OpenMCOperator(Operator): local_mats = _distribute(self.burnable_mats) # Determine which nuclides have incident neutron data - self._load_participating() + self.nuclides_with_data = self._get_nuclides_with_data() + self._burnable_nucs = [nuc for nuc in self.nuclides_with_data + if nuc in self.chain] # Extract number densities from the geometry self._extract_number(local_mats, volume, nuc_dict) @@ -152,7 +150,7 @@ class OpenMCOperator(Operator): # Create reaction rates array index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} self.reaction_rates = ReactionRates( - self.burn_mat_to_ind, self.burn_nuc_to_ind, index_rx) + self.burn_mat_to_ind, self._burnable_nucs, index_rx) def __call__(self, vec, print_out=True): """Runs a simulation. @@ -264,7 +262,7 @@ class OpenMCOperator(Operator): len(self.chain)) if self.settings.dilute_initial != 0.0: - for nuc in self.burn_nuc_to_ind: + for nuc in self._burnable_nucs: self.number.set_atom_density(np.s_[:], nuc, self.settings.dilute_initial) @@ -545,7 +543,7 @@ class OpenMCOperator(Operator): return OperatorResult(k_combined, rates) - def _load_participating(self): + def _get_nuclides_with_data(self): """Loads a cross_sections.xml file to find participating nuclides. This allows for nuclides that are important in the decay chain but not @@ -560,7 +558,7 @@ class OpenMCOperator(Operator): except KeyError: filename = None - self.nuclides_with_data = set() + nuclides = set() try: tree = ET.parse(filename) @@ -572,9 +570,6 @@ class OpenMCOperator(Operator): raise IOError(msg) root = tree.getroot() - self.burn_nuc_to_ind = OrderedDict() - nuc_ind = 0 - for nuclide_node in root.findall('library'): mats = nuclide_node.get('materials') if not mats: @@ -582,11 +577,10 @@ class OpenMCOperator(Operator): for name in mats.split(): # Make a burn list of the union of nuclides in cross_sections.xml # and nuclides in depletion chain. - if name not in self.nuclides_with_data: - self.nuclides_with_data.add(name) - if name in self.chain: - self.burn_nuc_to_ind[name] = nuc_ind - nuc_ind += 1 + if name not in nuclides: + nuclides.add(name) + + return nuclides def get_results_info(self): """Returns volume list, cell lists, and nuc lists. diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index a479085174..d1e1b0f1e2 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -15,8 +15,8 @@ class ReactionRates(np.ndarray): ---------- index_mat : OrderedDict of str to int A dictionary mapping material ID as string to index. - index_nuc : OrderedDict of str to int - A dictionary mapping nuclide name as string to index. + nuclides : list of str + Depletable nuclides index_rx : OrderedDict of str to int A dictionary mapping reaction name as string to index. @@ -36,15 +36,15 @@ class ReactionRates(np.ndarray): Number of reactions. """ - def __new__(cls, index_mat, index_nuc, index_rx): + def __new__(cls, index_mat, nuclides, index_rx): # Create appropriately-sized zeroed-out ndarray - shape = (len(index_mat), len(index_nuc), len(index_rx)) + shape = (len(index_mat), len(nuclides), len(index_rx)) obj = super().__new__(cls, shape) obj[:] = 0.0 # Add mapping attributes obj.index_mat = index_mat - obj.index_nuc = index_nuc + obj.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} obj.index_rx = index_rx return obj From 704a131f2d2039138e566216639011df5ddc102c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 16:38:45 -0600 Subject: [PATCH 143/212] Some refactoring of AtomNumber. Get rid of burn_mat_to_ind --- openmc/deplete/atom_number.py | 122 +++++++++---------- openmc/deplete/openmc_wrapper.py | 65 +++++----- openmc/deplete/results.py | 34 ------ tests/unit_tests/test_deplete_atom_number.py | 59 +++------ 4 files changed, 103 insertions(+), 177 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 3ad4968a82..1a142676cb 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -7,60 +7,55 @@ import numpy as np class AtomNumber(object): - """AtomNumber module. - - An ndarray to store atom densities with string, integer, or slice indexing. + """Stores local material compositions (atoms of each nuclide). Parameters ---------- - mat_to_ind : OrderedDict of str to int - A dictionary mapping material ID as string to index. - nuc_to_ind : OrderedDict of str to int - A dictionary mapping nuclide name as string to index. - volume : OrderedDict of int to float + local_mats : list of str + Material IDs + nuclides : list of str + Nuclides to be tracked + volume : dict Volume of each material in [cm^3] n_nuc_burn : int Number of nuclides to be burned. Attributes ---------- - mat_to_ind : OrderedDict of str to int - A dictionary mapping cell ID as string to index. - nuc_to_ind : OrderedDict of str to int - A dictionary mapping nuclide name as string to index. - volume : numpy.array - Volume of geometry indexed by mat_to_ind. If a volume is not found, - it defaults to 1 so that reading density still works correctly. + index_mat : dict + A dictionary mapping material ID as string to index. + index_nuc : dict + A dictionary mapping nuclide name to index. + volume : numpy.ndarray + Volume of each material in [cm^3]. If a volume is not found, it defaults + to 1 so that reading density still works correctly. + number : numpy.ndarray + Array storing total atoms for each material/nuclide + materials : list of str + Material IDs as strings + nuclides : list of str + All nuclide names + burnable_nuclides : list of str + Burnable nuclides names. Used for sorting the simulation. n_nuc_burn : int - Number of nuclides to be burned. - n_mat : int - Number of materials. + Number of burnable nuclides. n_nuc : int - Number of nucs. - number : numpy.array - Array storing total atoms indexed by the above dictionaries. - burn_nuc_list : list of str - A list of all nuclide material names. Used for sorting the simulation. + Number of nuclidess. """ - def __init__(self, mat_to_ind, nuc_to_ind, volume, n_nuc_burn): + def __init__(self, local_mats, nuclides, volume, n_nuc_burn): + self.index_mat = {mat: i for i, mat in enumerate(local_mats)} + self.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} - self.mat_to_ind = mat_to_ind - self.nuc_to_ind = nuc_to_ind - - self.volume = np.ones(len(mat_to_ind)) - - for mat in volume: - if mat in self.mat_to_ind: - ind = self.mat_to_ind[mat] - self.volume[ind] = volume[mat] + self.volume = np.ones(len(local_mats)) + for mat, val in volume.items(): + if mat in self.index_mat: + ind = self.index_mat[mat] + self.volume[ind] = val self.n_nuc_burn = n_nuc_burn - self.number = np.zeros((self.n_mat, self.n_nuc)) - - # For performance, create storage for burn_nuc_list, burn_mat_list - self._burn_nuc_list = None + self.number = np.zeros((len(local_mats), self.n_nuc)) def __getitem__(self, pos): """Retrieves total atom number from AtomNumber. @@ -80,9 +75,9 @@ class AtomNumber(object): mat, nuc = pos if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] + nuc = self.index_nuc[nuc] return self.number[mat, nuc] @@ -101,37 +96,30 @@ class AtomNumber(object): """ mat, nuc = pos if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] + nuc = self.index_nuc[nuc] self.number[mat, nuc] = val @property - def n_mat(self): - """Number of materials.""" - return len(self.mat_to_ind) + def materials(self): + return self.index_mat.keys() + + @property + def nuclides(self): + return self.index_nuc.keys() @property def n_nuc(self): """Number of nuclides.""" - return len(self.nuc_to_ind) + return len(self.index_nuc) @property - def burn_nuc_list(self): - """burn_nuc_list : list of str - A list of all nuclide material names. Used for sorting the simulation. - """ - - if self._burn_nuc_list is None: - self._burn_nuc_list = [None] * self.n_nuc_burn - - for nuc in self.nuc_to_ind: - ind = self.nuc_to_ind[nuc] - if ind < self.n_nuc_burn: - self._burn_nuc_list[ind] = nuc - - return self._burn_nuc_list + def burnable_nuclides(self): + """All burnable nuclide names. Used for sorting the simulation.""" + return [nuc for nuc, ind in self.index_nuc.items() + if ind < self.n_nuc_burn] def get_atom_density(self, mat, nuc): """Accesses atom density instead of total number. @@ -150,9 +138,9 @@ class AtomNumber(object): """ if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] + nuc = self.index_nuc[nuc] return self[mat, nuc] / self.volume[mat] @@ -170,9 +158,9 @@ class AtomNumber(object): """ if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] if isinstance(nuc, str): - nuc = self.nuc_to_ind[nuc] + nuc = self.index_nuc[nuc] self[mat, nuc] = val * self.volume[mat] @@ -191,7 +179,7 @@ class AtomNumber(object): """ if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] return self[mat, :self.n_nuc_burn] @@ -207,7 +195,7 @@ class AtomNumber(object): """ if isinstance(mat, str): - mat = self.mat_to_ind[mat] + mat = self.index_mat[mat] self[mat, :self.n_nuc_burn] = val @@ -223,5 +211,5 @@ class AtomNumber(object): Total atoms. """ - for i in range(self.n_mat): - self.set_mat_slice(i, total_density[i]) + for i, density_slice in enumerate(total_density): + self.set_mat_slice(i, density_slice) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 3c3b974c90..7d776825b0 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -121,10 +121,10 @@ class OpenMCOperator(Operator): The depletion chain information necessary to form matrices and tallies. reaction_rates : openmc.deplete.ReactionRates Reaction rates from the last operator step. - burn_mat_to_ind : OrderedDict of str to int - Dictionary mapping material ID (as a string) to an index in reaction_rates. burnable_mats : list of str All burnable material IDs + local_mats : list of str + All burnable material IDs being managed by a single process """ def __init__(self, geometry, settings): @@ -136,8 +136,8 @@ class OpenMCOperator(Operator): # Clear out OpenMC, create task lists, distribute openmc.reset_auto_ids() - self.burnable_mats, volume, nuc_dict = self._get_burnable_mats() - local_mats = _distribute(self.burnable_mats) + self.burnable_mats, volume, nuclides = self._get_burnable_mats() + self.local_mats = _distribute(self.burnable_mats) # Determine which nuclides have incident neutron data self.nuclides_with_data = self._get_nuclides_with_data() @@ -145,12 +145,12 @@ class OpenMCOperator(Operator): if nuc in self.chain] # Extract number densities from the geometry - self._extract_number(local_mats, volume, nuc_dict) + self._extract_number(self.local_mats, volume, nuclides) # Create reaction rates array index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} self.reaction_rates = ReactionRates( - self.burn_mat_to_ind, self._burnable_nucs, index_rx) + self.local_mats, self._burnable_nucs, index_rx) def __call__(self, vec, print_out=True): """Runs a simulation. @@ -207,7 +207,7 @@ class OpenMCOperator(Operator): List of burnable material IDs volume : OrderedDict of str to float Volume of each material in [cm^3] - nuc_dict : OrderedDict of str to int + nuclides : list of str Nuclides in order of how they'll appear in the simulation. """ @@ -231,16 +231,14 @@ class OpenMCOperator(Operator): model_nuclides = sorted(model_nuclides) # Construct a global nuclide dictionary, burned first - nuc_dict = copy.deepcopy(self.chain.nuclide_dict) - i = len(nuc_dict) + nuclides = list(self.chain.nuclide_dict) for nuc in model_nuclides: - if nuc not in nuc_dict: - nuc_dict[nuc] = i - i += 1 + if nuc not in nuclides: + nuclides.append(nuc) - return burnable_mats, volume, nuc_dict + return burnable_mats, volume, nuclides - def _extract_number(self, local_mats, volume, nuc_dict): + def _extract_number(self, local_mats, volume, nuclides): """Construct AtomNumber using geometry Parameters @@ -249,17 +247,11 @@ class OpenMCOperator(Operator): Material IDs to be managed by this process volume : OrderedDict of str to float Volumes for the above materials in [cm^3] - nuc_dict : OrderedDict of str to int + nuclides : list of str Nuclides to be used in the simulation. """ - # Same with materials - self.burn_mat_to_ind = OrderedDict() - for i, mat in enumerate(local_mats): - self.burn_mat_to_ind[mat] = i - - self.number = AtomNumber(self.burn_mat_to_ind, nuc_dict, volume, - len(self.chain)) + self.number = AtomNumber(local_mats, nuclides, volume, len(self.chain)) if self.settings.dilute_initial != 0.0: for nuc in self._burnable_nucs: @@ -268,7 +260,7 @@ class OpenMCOperator(Operator): # Now extract the number densities and store for mat in self.geometry.get_all_materials().values(): - if str(mat.id) in self.burn_mat_to_ind: + if str(mat.id) in local_mats: self._set_number_from_mat(mat) def _set_number_from_mat(self, mat): @@ -281,7 +273,6 @@ class OpenMCOperator(Operator): """ mat_id = str(mat.id) - mat_ind = self.number.mat_to_ind[mat_id] for nuclide, density in mat.get_nuclide_atom_densities().values(): number = density * 1.0e24 @@ -293,7 +284,7 @@ class OpenMCOperator(Operator): Parameters ---------- y : numpy.ndarray - An array representing reaction rates for this cell. + An array representing reaction rates for this material. mat : int Material id. @@ -340,10 +331,10 @@ class OpenMCOperator(Operator): for rank in range(comm.size): number_i = comm.bcast(self.number, root=rank) - for mat in number_i.mat_to_ind: + for mat in number_i.materials: nuclides = [] densities = [] - for nuc in number_i.nuc_to_ind: + for nuc in number_i.nuclides: if nuc in self.nuclides_with_data: val = 1.0e-24 * number_i.get_atom_density(mat, nuc) @@ -381,7 +372,7 @@ class OpenMCOperator(Operator): .values()) # Sort nuclides according to order in AtomNumber object - nuclides = list(self.number.nuc_to_ind.keys()) + nuclides = list(self.number.nuclides) for mat in materials: mat._nuclides.sort(key=lambda x: nuclides.index(x[0])) @@ -404,9 +395,9 @@ class OpenMCOperator(Operator): """ nuc_set = set() - # Create the set of all nuclides in the decay chain in cells marked for - # burning in which the number density is greater than zero. - for nuc in self.number.nuc_to_ind: + # Create the set of all nuclides in the decay chain in materials marked + # for burning in which the number density is greater than zero. + for nuc in self.number.nuclides: if nuc in self.nuclides_with_data: if np.sum(self.number[:, nuc]) > 0.0: nuc_set.add(nuc) @@ -421,7 +412,7 @@ class OpenMCOperator(Operator): if comm.rank == 0: # Sort nuclides in the same order as self.number - nuc_list = [nuc for nuc in self.number.nuc_to_ind + nuc_list = [nuc for nuc in self.number.nuclides if nuc in nuc_set] else: nuc_list = None @@ -502,7 +493,7 @@ class OpenMCOperator(Operator): break # Extract results - for i, mat in enumerate(self.burn_mat_to_ind): + for i, mat in enumerate(self.local_mats): # Get tally index slab = materials.index(mat) @@ -583,7 +574,7 @@ class OpenMCOperator(Operator): return nuclides def get_results_info(self): - """Returns volume list, cell lists, and nuc lists. + """Returns volume list, material lists, and nuc lists. Returns ------- @@ -592,13 +583,13 @@ class OpenMCOperator(Operator): nuc_list : list of str A list of all nuclide names. Used for sorting the simulation. burn_list : list of int - A list of all cell IDs to be burned. Used for sorting the simulation. + A list of all material IDs to be burned. Used for sorting the simulation. full_burn_list : list List of all burnable material IDs """ - nuc_list = self.number.burn_nuc_list - burn_list = list(self.burn_mat_to_ind) + nuc_list = self.number.burnable_nuclides + burn_list = self.local_mats volume = {} for i, mat in enumerate(burn_list): diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index f7daca5b2e..e18051d9d8 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -346,40 +346,6 @@ class Results(object): return results -def get_dict(number): - """Given an operator nested dictionary, output indexing dictionaries. - - These indexing dictionaries map mat IDs and nuclide names to indices - inside of Results.data. - - Parameters - ---------- - number : AtomNumber - The object to extract dictionaries from - - Returns - ------- - mat_to_ind : OrderedDict of str to int - Maps mat strings to index in array. - nuc_to_ind : OrderedDict of str to int - Maps nuclide strings to index in array. - """ - mat_to_ind = OrderedDict() - nuc_to_ind = OrderedDict() - - for nuc in number.nuc_to_ind: - nuc_ind = number.nuc_to_ind[nuc] - if nuc_ind < number.n_nuc_burn: - nuc_to_ind[nuc] = nuc_ind - - for mat in number.mat_to_ind: - mat_ind = number.mat_to_ind[mat] - if mat_ind < number.n_mat_burn: - mat_to_ind[mat] = mat_ind - - return mat_to_ind, nuc_to_ind - - def write_results(result, filename, index): """Outputs result to an .hdf5 file. diff --git a/tests/unit_tests/test_deplete_atom_number.py b/tests/unit_tests/test_deplete_atom_number.py index 887e9af1bc..4cc9207ca9 100644 --- a/tests/unit_tests/test_deplete_atom_number.py +++ b/tests/unit_tests/test_deplete_atom_number.py @@ -7,11 +7,11 @@ from openmc.deplete import atom_number def test_indexing(): """Tests the __getitem__ and __setitem__ routines simultaneously.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "U234"] volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) number["10000", "U238"] = 1.0 number["10001", "U238"] = 2.0 @@ -36,47 +36,28 @@ def test_indexing(): assert number["10000", "U238"] == 5.0 -def test_n_mat(): - """Test number of materials property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} +def test_properties(): + """Test properties. """ + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "Gd157"] volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) - - assert number.n_mat == 2 - - -def test_n_nuc(): - """Test number of nuclides property.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) + assert list(number.materials) == ["10000", "10001"] assert number.n_nuc == 3 - - -def test_burn_nuc_list(): - """Test the list of burned nuclides property""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - volume = {"10000" : 0.38, "10001" : 0.21} - - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) - - assert number.burn_nuc_list == ["U238", "U235"] + assert list(number.nuclides) == ["U238", "U235", "Gd157"] + assert number.burnable_nuclides == ["U238", "U235"] def test_density_indexing(): """Tests the get and set_atom_density routines simultaneously.""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) number.set_atom_density("10000", "U238", 1.0) number.set_atom_density("10001", "U238", 2.0) @@ -129,11 +110,11 @@ def test_density_indexing(): def test_get_mat_slice(): """Tests getting slices.""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) number.number = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) @@ -149,11 +130,11 @@ def test_get_mat_slice(): def test_set_mat_slice(): """Tests getting slices.""" - mat_to_ind = {"10000" : 0, "10001" : 1, "10002" : 2} - nuc_to_ind = {"U238" : 0, "U235" : 1, "U234" : 2} + local_mats = ["10000", "10001", "10002"] + nuclides = ["U238", "U235", "U234"] volume = {"10000" : 0.38, "10001" : 0.21} - number = atom_number.AtomNumber(mat_to_ind, nuc_to_ind, volume, 2) + number = atom_number.AtomNumber(local_mats, nuclides, volume, 2) number.set_mat_slice(0, [1.0, 2.0]) From c19f396aa77b78efe0658ba4d4cc7356b1d8d780 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 16:49:51 -0600 Subject: [PATCH 144/212] Remove Operator.form_matrix methods (Chain owns these) --- openmc/deplete/abc.py | 22 ---------------------- openmc/deplete/openmc_wrapper.py | 18 ------------------ 2 files changed, 40 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index e8f65f8871..6916066816 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -133,27 +133,5 @@ class Operator(metaclass=ABCMeta): pass - @abstractmethod - def form_matrix(self, y, mat): - """Forms the f(y) matrix in y' = f(y)y. - - Nominally a depletion matrix, this is abstracted on the off chance - that the function f has nothing to do with depletion at all. - - Parameters - ---------- - y : numpy.ndarray - An array representing y. - mat : int - Material id. - - Returns - ------- - scipy.sparse.csr_matrix - Sparse matrix representing f(y). - """ - - pass - def finalize(self): pass diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 7d776825b0..56a248c30c 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -278,24 +278,6 @@ class OpenMCOperator(Operator): number = density * 1.0e24 self.number.set_atom_density(mat_id, nuclide, number) - def form_matrix(self, y, mat): - """Forms the depletion matrix. - - Parameters - ---------- - y : numpy.ndarray - An array representing reaction rates for this material. - mat : int - Material id. - - Returns - ------- - scipy.sparse.csr_matrix - Sparse matrix representing the depletion matrix. - """ - - return copy.deepcopy(self.chain.form_matrix(y[mat, :, :])) - def initial_condition(self): """Performs final setup and returns initial condition. From ccfee55115a10144a04e63eac2e744b7411d1c82 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 17:26:44 -0600 Subject: [PATCH 145/212] Make timesteps and power specified in integrator functions --- openmc/deplete/abc.py | 8 ------- openmc/deplete/integrator/cecm.py | 24 ++++++++++++++----- openmc/deplete/integrator/predictor.py | 26 +++++++++++++++------ openmc/deplete/openmc_wrapper.py | 23 +++++++++++------- tests/dummy_geometry.py | 4 +++- tests/regression_tests/test_deplete_full.py | 17 +++++++------- tests/unit_tests/test_deplete_cecm.py | 5 ++-- tests/unit_tests/test_deplete_predictor.py | 5 ++-- 8 files changed, 68 insertions(+), 44 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 6916066816..7fda93aa28 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -18,8 +18,6 @@ class Settings(object): Attributes ---------- - dt_vec : numpy.array - Array of time steps to take. output_dir : pathlib.Path Path to output directory to save results. chain_file : str @@ -29,10 +27,6 @@ class Settings(object): Initial atom density to add for nuclides that are zero in initial condition to ensure they exist in the decay chain. Only done for nuclides with reaction rates. Defaults to 1.0e3. - power : float - Power of the reactor in [W]. For a 2D problem, the power can be given in - W/cm as long as the "volume" assigned to a depletion material is - actually an area in cm^2. """ def __init__(self): @@ -40,9 +34,7 @@ class Settings(object): self.chain_file = os.environ["OPENMC_DEPLETE_CHAIN"] except KeyError: self.chain_file = None - self.dt_vec = None self.output_dir = '.' - self.power = None self.dilute_initial = 1.0e3 @property diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 760e3c89d8..7d6c11190f 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -1,12 +1,13 @@ """The CE/CM integrator.""" import copy +from collections.abc import Iterable from .cram import deplete from .save_results import save_results -def cecm(operator, print_out=True): +def cecm(operator, timesteps, power, print_out=True): r"""The CE/CM integrator. Implements the second order CE/CM Predictor-Corrector algorithm [ref]_. @@ -32,25 +33,36 @@ def cecm(operator, print_out=True): ---------- operator : openmc.deplete.Operator The operator object to simulate on. + timesteps : iterable of float + Array of timesteps in units of [s] + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power is + constant over all timesteps. An iterable indicates potentially different + power levels for each timestep. For a 2D problem, the power can be given + in [W/cm] as long as the "volume" assigned to a depletion material is + actually an area in [cm^2]. print_out : bool, optional Whether or not to print out time. """ + if not isinstance(power, Iterable): + power = [power]*len(timesteps) + # Generate initial conditions with operator as vec: chain = operator.chain t = 0.0 - for i, dt in enumerate(operator.settings.dt_vec): + for i, (dt, p) in enumerate(zip(timesteps, power)): # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - results = [operator(x[0])] + results = [operator(x[0], p)] # Deplete for first half of timestep x_middle = deplete(chain, x[0], results[0], dt/2, print_out) # Get middle-of-timestep reaction rates x.append(x_middle) - results.append(operator(x_middle)) + results.append(operator(x_middle, p)) # Deplete for full timestep using beginning-of-step materials x_end = deplete(chain, x[0], results[1], dt, print_out) @@ -64,7 +76,7 @@ def cecm(operator, print_out=True): # Perform one last simulation x = [copy.deepcopy(vec)] - results = [operator(x[0])] + results = [operator(x[0], power[-1])] # Create results, write to disk - save_results(operator, x, results, [t, t], len(operator.settings.dt_vec)) + save_results(operator, x, results, [t, t], len(timesteps)) diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 0640783318..038c0778da 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -1,13 +1,14 @@ -"""The Predictor algorithm.""" +"""First-order predictor algorithm.""" import copy +from collections.abc import Iterable from .cram import deplete from .save_results import save_results -def predictor(operator, print_out=True): - r"""The basic predictor integrator. +def predictor(operator, timesteps, power, print_out=True): + r"""Deplete using a first-order predictor algorithm. Implements the first-order predictor algorithm. This algorithm is mathematically defined as: @@ -23,18 +24,29 @@ def predictor(operator, print_out=True): ---------- operator : openmc.deplete.Operator The operator object to simulate on. + timesteps : iterable of float + Array of timesteps in units of [s] + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power is + constant over all timesteps. An iterable indicates potentially different + power levels for each timestep. For a 2D problem, the power can be given + in [W/cm] as long as the "volume" assigned to a depletion material is + actually an area in [cm^2]. print_out : bool, optional Whether or not to print out time. """ + if not isinstance(power, Iterable): + power = [power]*len(timesteps) + # Generate initial conditions with operator as vec: chain = operator.chain t = 0.0 - for i, dt in enumerate(operator.settings.dt_vec): + for i, (dt, p) in enumerate(zip(timesteps, power)): # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - results = [operator(x[0])] + results = [operator(x[0], p)] # Create results, write to disk save_results(operator, x, results, [t, t + dt], i) @@ -48,7 +60,7 @@ def predictor(operator, print_out=True): # Perform one last simulation x = [copy.deepcopy(vec)] - results = [operator(x[0])] + results = [operator(x[0], power[-1])] # Create results, write to disk - save_results(operator, x, results, [t, t], len(operator.settings.dt_vec)) + save_results(operator, x, results, [t, t], len(timesteps)) diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 56a248c30c..e5898997bc 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -45,8 +45,6 @@ class OpenMCSettings(Settings): Attributes ---------- - dt_vec : numpy.array - Array of time steps to in units of [s] output_dir : pathlib.Path Path to output directory to save results. chain_file : str @@ -68,8 +66,8 @@ class OpenMCSettings(Settings): """ - _depletion_attrs = {'dt_vec', '_output_dir', 'chain_file', 'dilute_initial', - 'round_number', 'power'} + _depletion_attrs = {'_output_dir', 'chain_file', 'dilute_initial', + 'round_number'} def __init__(self): super().__init__() @@ -152,13 +150,15 @@ class OpenMCOperator(Operator): self.reaction_rates = ReactionRates( self.local_mats, self._burnable_nucs, index_rx) - def __call__(self, vec, print_out=True): + def __call__(self, vec, power, print_out=True): """Runs a simulation. Parameters ---------- vec : list of numpy.array Total atoms to be used in function. + power : float + Power of the reactor in [W] print_out : bool, optional Whether or not to print out time. @@ -187,7 +187,7 @@ class OpenMCOperator(Operator): time_openmc = time.time() # Extract results - op_result = self._unpack_tallies_and_normalize() + op_result = self._unpack_tallies_and_normalize(power) if comm.rank == 0: time_unpack = time.time() @@ -424,7 +424,7 @@ class OpenMCOperator(Operator): self._tally.scores = self.chain.reactions self._tally.filters = [mat_filter] - def _unpack_tallies_and_normalize(self): + def _unpack_tallies_and_normalize(self, power): """Unpack tallies from OpenMC and return an operator result This method uses OpenMC's C API bindings to determine the k-effective @@ -432,6 +432,11 @@ class OpenMCOperator(Operator): normalized by the user-specified power, summing the product of the fission reaction rate times the fission Q value for each material. + Parameters + ---------- + power : float + Power of the reactor in [W] + Returns ------- openmc.deplete.OperatorResult @@ -509,10 +514,10 @@ class OpenMCOperator(Operator): energy = comm.allreduce(energy) # Determine power in eV/s - power = self.settings.power / JOULE_PER_EV + power /= JOULE_PER_EV # Scale reaction rates to obtain units of reactions/sec - rates[:, :, :] *= power / energy + rates *= power / energy return OperatorResult(k_combined, rates) diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index c013bb0054..d662616698 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -21,13 +21,15 @@ class DummyGeometry(Operator): def __init__(self, settings): super().__init__(settings) - def __call__(self, vec, print_out=False): + def __call__(self, vec, power, print_out=False): """Evaluates F(y) Parameters ---------- vec : list of numpy.array Total atoms to be used in function. + power : float + Power in [W] print_out : bool, optional, ignored Whether or not to print out time. diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 6033e3f75a..1ae2cee1fa 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -32,18 +32,10 @@ def test_full(run_in_tmpdir): # Load geometry from example geometry, lower_left, upper_right = generate_problem(n_rings, n_wedges) - # Create dt vector for 3 steps with 15 day timesteps - dt1 = 15.*24*60*60 # 15 days - dt2 = 1.5*30*24*60*60 # 1.5 months - N = floor(dt2/dt1) - dt = np.full(N, dt1) - # Depletion settings settings = openmc.deplete.OpenMCSettings() settings.chain_file = str(Path(__file__).parents[2] / 'chains' / 'chain_simple.xml') - settings.power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO - settings.dt_vec = dt settings.round_number = True # Add OpenMC-specific settings @@ -57,8 +49,15 @@ def test_full(run_in_tmpdir): op = openmc.deplete.OpenMCOperator(geometry, settings) + # Power and timesteps + dt1 = 15.*24*60*60 # 15 days + dt2 = 1.5*30*24*60*60 # 1.5 months + N = floor(dt2/dt1) + dt = np.full(N, dt1) + power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO + # Perform simulation using the predictor algorithm - openmc.deplete.integrator.predictor(op) + openmc.deplete.integrator.predictor(op, dt, power) # Get path to test and reference results path_test = settings.output_dir / 'depletion_results.h5' diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 66c3ee156c..3daa7a0489 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -15,13 +15,14 @@ def test_cecm(run_in_tmpdir): """Integral regression test of integrator algorithm using CE/CM.""" settings = openmc.deplete.Settings() - settings.dt_vec = [0.75, 0.75] settings.output_dir = "test_integrator_regression" op = dummy_geometry.DummyGeometry(settings) # Perform simulation using the MCNPX/MCNP6 algorithm - openmc.deplete.cecm(op, print_out=False) + dt = [0.75, 0.75] + power = 1.0 + openmc.deplete.cecm(op, dt, power, print_out=False) # Load the files res = results.read_results(settings.output_dir / "depletion_results.h5") diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index f1133f87d2..be8497f5f7 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -15,13 +15,14 @@ def test_predictor(run_in_tmpdir): """Integral regression test of integrator algorithm using predictor/corrector""" settings = openmc.deplete.Settings() - settings.dt_vec = [0.75, 0.75] settings.output_dir = "test_integrator_regression" op = dummy_geometry.DummyGeometry(settings) # Perform simulation using the predictor algorithm - openmc.deplete.predictor(op, print_out=False) + dt = [0.75, 0.75] + power = 1.0 + openmc.deplete.predictor(op, dt, power, print_out=False) # Load the files res = results.read_results(settings.output_dir / "depletion_results.h5") From a460782691b86bf932c2acbcdba76ceb6c914659 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 17:52:17 -0600 Subject: [PATCH 146/212] Get rid of extra Settings class --- docs/source/pythonapi/deplete/index.rst | 2 - openmc/deplete/abc.py | 75 +++++++-------- openmc/deplete/chain.py | 14 +-- openmc/deplete/openmc_wrapper.py | 100 ++++++-------------- tests/dummy_geometry.py | 5 +- tests/regression_tests/test_deplete_full.py | 16 ++-- tests/unit_tests/test_deplete_cecm.py | 8 +- tests/unit_tests/test_deplete_predictor.py | 8 +- 8 files changed, 77 insertions(+), 151 deletions(-) diff --git a/docs/source/pythonapi/deplete/index.rst b/docs/source/pythonapi/deplete/index.rst index 30d2d42611..f3212bd61d 100644 --- a/docs/source/pythonapi/deplete/index.rst +++ b/docs/source/pythonapi/deplete/index.rst @@ -29,7 +29,6 @@ Metaclasses :toctree: generated :nosignatures: - openmc.deplete.Settings openmc.deplete.Operator OpenMC Classes @@ -39,7 +38,6 @@ OpenMC Classes :toctree: generated :nosignatures: - openmc.deplete.OpenMCSettings openmc.deplete.Materials openmc.deplete.OpenMCOperator diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 7fda93aa28..9d53f40bfd 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -7,44 +7,9 @@ to run a full depletion simulation. from collections import namedtuple import os from pathlib import Path - from abc import ABCMeta, abstractmethod - -class Settings(object): - """The Settings class. - - Contains all parameters necessary for the integrator. - - Attributes - ---------- - output_dir : pathlib.Path - Path to output directory to save results. - chain_file : str - Path to the depletion chain XML file. Defaults to the - :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. - dilute_initial : float - Initial atom density to add for nuclides that are zero in initial - condition to ensure they exist in the decay chain. Only done for - nuclides with reaction rates. Defaults to 1.0e3. - - """ - def __init__(self): - try: - self.chain_file = os.environ["OPENMC_DEPLETE_CHAIN"] - except KeyError: - self.chain_file = None - self.output_dir = '.' - self.dilute_initial = 1.0e3 - - @property - def output_dir(self): - return self._output_dir - - @output_dir.setter - def output_dir(self, output_dir): - self._output_dir = Path(output_dir) - +from .chain import Chain OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) @@ -52,14 +17,30 @@ OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) class Operator(metaclass=ABCMeta): """Abstract class defining a transport operator + Parameters + ---------- + chain_file : str, optional + + Attributes ---------- - settings : Settings - Settings object. + dilute_initial : float + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. Defaults to 1.0e3. """ - def __init__(self, settings): - self.settings = settings + def __init__(self, chain_file=None): + self.dilute_initial = 1.0e3 + self.output_dir = '.' + + # Read depletion chain + if chain_file is None: + chain_file = os.environ.get("OPENMC_DEPLETE_CHAIN", None) + if chain_file is None: + raise IOError("No chain specified, either manually or in " + "environment variable OPENMC_DEPLETE_CHAIN.") + self.chain = Chain.from_xml(chain_file) @abstractmethod def __call__(self, vec, print_out=True): @@ -83,11 +64,11 @@ class Operator(metaclass=ABCMeta): def __enter__(self): # Save current directory and move to specific output directory self._orig_dir = os.getcwd() - if not self.settings.output_dir.exists(): - self.settings.output_dir.mkdir() # exist_ok parameter is 3.5+ + if not self.output_dir.exists(): + self.output_dir.mkdir() # exist_ok parameter is 3.5+ # In Python 3.6+, chdir accepts a Path directly - os.chdir(str(self.settings.output_dir)) + os.chdir(str(self.output_dir)) return self.initial_condition() @@ -95,6 +76,14 @@ class Operator(metaclass=ABCMeta): self.finalize() os.chdir(self._orig_dir) + @property + def output_dir(self): + return self._output_dir + + @output_dir.setter + def output_dir(self, output_dir): + self._output_dir = Path(output_dir) + @abstractmethod def initial_condition(self): """Performs final setup and returns initial condition. diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index ec8d79f819..9ffc3d93ec 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -328,15 +328,7 @@ class Chain(object): chain = cls() # Load XML tree - try: - root = ET.parse(filename) - except Exception: - if filename is None: - msg = ("No chain specified, either manually or in environment " - "variable OPENMC_DEPLETE_CHAIN.") - else: - msg = 'Decay chain "{}" is invalid.'.format(filename) - raise IOError(msg) + root = ET.parse(str(filename)) for i, nuclide_elem in enumerate(root.findall('nuclide_table')): nuc = Nuclide.from_xml(nuclide_elem) @@ -367,10 +359,10 @@ class Chain(object): tree = ET.ElementTree(root_elem) if _have_lxml: - tree.write(filename, encoding='utf-8', pretty_print=True) + tree.write(str(filename), encoding='utf-8', pretty_print=True) else: clean_xml_indentation(root_elem) - tree.write(filename, encoding='utf-8') + tree.write(str(filename), encoding='utf-8') def form_matrix(self, rates): """Forms depletion matrix. diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index e5898997bc..12ed27f229 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -24,9 +24,8 @@ import openmc import openmc.capi from openmc.data import JOULE_PER_EV from . import comm -from .abc import Settings, Operator, OperatorResult +from .abc import Operator, OperatorResult from .atom_number import AtomNumber -from .chain import Chain from .reaction_rates import ReactionRates @@ -40,77 +39,34 @@ def _distribute(items): j += chunk_size -class OpenMCSettings(Settings): - """Extends Settings to provide information OpenMC needs to run. - - Attributes - ---------- - output_dir : pathlib.Path - Path to output directory to save results. - chain_file : str - Path to the depletion chain XML file. Defaults to the - :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. - dilute_initial : float - Initial atom density to add for nuclides that are zero in initial - condition to ensure they exist in the decay chain. Only done for - nuclides with reaction rates. Defaults to 1.0e3. - power : float - Power of the reactor in [W]. For a 2D problem, the power can be given in - W/cm as long as the "volume" assigned to a depletion material is - actually an area in cm^2. - round_number : bool - Whether or not to round output to OpenMC to 8 digits. - Useful in testing, as OpenMC is incredibly sensitive to exact values. - settings : openmc.Settings - Settings for OpenMC simulations - - """ - - _depletion_attrs = {'_output_dir', 'chain_file', 'dilute_initial', - 'round_number'} - - def __init__(self): - super().__init__() - self.round_number = False - - # Avoid setattr to create OpenMC settings - self.__dict__['settings'] = openmc.Settings() - - def __setattr__(self, name, value): - if hasattr(self.__class__, name): - # Use properties when appropriate - prop = getattr(self.__class__, name) - prop.fset(self, value) - elif name in self._depletion_attrs: - # For known attributes, store in dictionary - self.__dict__[name] = value - else: - # otherwise, delegate to openmc.Settings - setattr(self.__dict__['settings'], name, value) - - def __getattr__(self, name): - if name in self._depletion_attrs: - return self.__dict__[name] - else: - return getattr(self.__dict__['settings'], name) - - class OpenMCOperator(Operator): """OpenMC transport operator Parameters ---------- geometry : openmc.Geometry - The OpenMC geometry object. - settings : openmc.deplete.OpenMCSettings - Settings object. + OpenMC geometry object + settings : openmc.Settings + OpenMC Settings object + chain_file : str, optional + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. Attributes ---------- - settings : OpenMCSettings - Settings object. (From Operator) geometry : openmc.Geometry - The OpenMC geometry object. + OpenMC geometry object + settings : openmc.Settings + OpenMC settings object + dilute_initial : float + Initial atom density to add for nuclides that are zero in initial + condition to ensure they exist in the decay chain. Only done for + nuclides with reaction rates. Defaults to 1.0e3. + output_dir : pathlib.Path + Path to output directory to save results. + round_number : bool + Whether or not to round output to OpenMC to 8 digits. + Useful in testing, as OpenMC is incredibly sensitive to exact values. number : openmc.deplete.AtomNumber Total number of atoms in simulation. nuclides_with_data : set of str @@ -125,13 +81,12 @@ class OpenMCOperator(Operator): All burnable material IDs being managed by a single process """ - def __init__(self, geometry, settings): - super().__init__(settings) + def __init__(self, geometry, settings, chain_file=None): + super().__init__(chain_file) + self.round_number = False + self.settings = settings self.geometry = geometry - # Read depletion chain - self.chain = Chain.from_xml(settings.chain_file) - # Clear out OpenMC, create task lists, distribute openmc.reset_auto_ids() self.burnable_mats, volume, nuclides = self._get_burnable_mats() @@ -253,10 +208,9 @@ class OpenMCOperator(Operator): """ self.number = AtomNumber(local_mats, nuclides, volume, len(self.chain)) - if self.settings.dilute_initial != 0.0: + if self.dilute_initial != 0.0: for nuc in self._burnable_nucs: - self.number.set_atom_density(np.s_[:], nuc, - self.settings.dilute_initial) + self.number.set_atom_density(np.s_[:], nuc, self.dilute_initial) # Now extract the number densities and store for mat in self.geometry.get_all_materials().values(): @@ -290,7 +244,7 @@ class OpenMCOperator(Operator): # Create XML files if comm.rank == 0: self.geometry.export_to_xml() - self.settings.settings.export_to_xml() + self.settings.export_to_xml() self._generate_materials_xml() # Initialize OpenMC library @@ -322,7 +276,7 @@ class OpenMCOperator(Operator): # If nuclide is zero, do not add to the problem. if val > 0.0: - if self.settings.round_number: + if self.round_number: val_magnitude = np.floor(np.log10(val)) val_scaled = val / 10**val_magnitude val_round = round(val_scaled, 8) diff --git a/tests/dummy_geometry.py b/tests/dummy_geometry.py index d662616698..ca2efd6630 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_geometry.py @@ -17,9 +17,8 @@ class DummyGeometry(Operator): y_2(1.5) ~ 3.1726475740397628 """ - - def __init__(self, settings): - super().__init__(settings) + def __init__(self): + pass def __call__(self, vec, power, print_out=False): """Evaluates F(y) diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 1ae2cee1fa..22125d039d 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -32,13 +32,8 @@ def test_full(run_in_tmpdir): # Load geometry from example geometry, lower_left, upper_right = generate_problem(n_rings, n_wedges) - # Depletion settings - settings = openmc.deplete.OpenMCSettings() - settings.chain_file = str(Path(__file__).parents[2] / 'chains' / - 'chain_simple.xml') - settings.round_number = True - - # Add OpenMC-specific settings + # OpenMC-specific settings + settings = openmc.Settings() settings.particles = 100 settings.batches = 100 settings.inactive = 40 @@ -47,7 +42,10 @@ def test_full(run_in_tmpdir): settings.seed = 1 settings.verbosity = 3 - op = openmc.deplete.OpenMCOperator(geometry, settings) + # Create operator + chain_file = Path(__file__).parents[2] / 'chains' / 'chain_simple.xml' + op = openmc.deplete.OpenMCOperator(geometry, settings, chain_file) + op.round_number = True # Power and timesteps dt1 = 15.*24*60*60 # 15 days @@ -60,7 +58,7 @@ def test_full(run_in_tmpdir): openmc.deplete.integrator.predictor(op, dt, power) # Get path to test and reference results - path_test = settings.output_dir / 'depletion_results.h5' + path_test = op.output_dir / 'depletion_results.h5' path_reference = Path(__file__).with_name('test_reference.h5') # If updating results, do so and return diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 3daa7a0489..97659b8923 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -14,10 +14,8 @@ from tests import dummy_geometry def test_cecm(run_in_tmpdir): """Integral regression test of integrator algorithm using CE/CM.""" - settings = openmc.deplete.Settings() - settings.output_dir = "test_integrator_regression" - - op = dummy_geometry.DummyGeometry(settings) + op = dummy_geometry.DummyGeometry() + op.output_dir = "test_integrator_regression" # Perform simulation using the MCNPX/MCNP6 algorithm dt = [0.75, 0.75] @@ -25,7 +23,7 @@ def test_cecm(run_in_tmpdir): openmc.deplete.cecm(op, dt, power, print_out=False) # Load the files - res = results.read_results(settings.output_dir / "depletion_results.h5") + res = results.read_results(op.output_dir / "depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index be8497f5f7..42a3c13a3a 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -14,10 +14,8 @@ from tests import dummy_geometry def test_predictor(run_in_tmpdir): """Integral regression test of integrator algorithm using predictor/corrector""" - settings = openmc.deplete.Settings() - settings.output_dir = "test_integrator_regression" - - op = dummy_geometry.DummyGeometry(settings) + op = dummy_geometry.DummyGeometry() + op.output_dir = "test_integrator_regression" # Perform simulation using the predictor algorithm dt = [0.75, 0.75] @@ -25,7 +23,7 @@ def test_predictor(run_in_tmpdir): openmc.deplete.predictor(op, dt, power, print_out=False) # Load the files - res = results.read_results(settings.output_dir / "depletion_results.h5") + res = results.read_results(op.output_dir / "depletion_results.h5") _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") From a9df0465f0d7344d7156473657a575badf354c77 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 22:51:53 -0600 Subject: [PATCH 147/212] Start cleaning up documentation --- docs/source/conf.py | 14 +++-- docs/source/pythonapi/deplete.rst | 62 +++++++++++++++++++ docs/source/pythonapi/deplete/index.rst | 54 ---------------- .../pythonapi/deplete/integrator.CRAM16.rst | 6 -- .../pythonapi/deplete/integrator.CRAM48.rst | 6 -- .../pythonapi/deplete/integrator.cecm.rst | 6 -- .../deplete/integrator.predictor.rst | 6 -- .../deplete/integrator.save_results.rst | 6 -- docs/source/pythonapi/index.rst | 6 +- openmc/deplete/abc.py | 22 ++++++- openmc/deplete/chain.py | 3 - openmc/deplete/integrator/cecm.py | 16 ++--- openmc/deplete/integrator/cram.py | 28 +++------ openmc/deplete/integrator/predictor.py | 4 +- openmc/deplete/integrator/save_results.py | 2 +- openmc/deplete/openmc_wrapper.py | 14 +++-- .../{dummy_geometry.py => dummy_operator.py} | 6 +- tests/regression_tests/test_deplete_full.py | 2 +- .../test_deplete_utilities.py | 2 +- tests/unit_tests/test_deplete_cecm.py | 4 +- tests/unit_tests/test_deplete_predictor.py | 4 +- 21 files changed, 131 insertions(+), 142 deletions(-) create mode 100644 docs/source/pythonapi/deplete.rst delete mode 100644 docs/source/pythonapi/deplete/index.rst delete mode 100644 docs/source/pythonapi/deplete/integrator.CRAM16.rst delete mode 100644 docs/source/pythonapi/deplete/integrator.CRAM48.rst delete mode 100644 docs/source/pythonapi/deplete/integrator.cecm.rst delete mode 100644 docs/source/pythonapi/deplete/integrator.predictor.rst delete mode 100644 docs/source/pythonapi/deplete/integrator.save_results.rst rename tests/{dummy_geometry.py => dummy_operator.py} (95%) diff --git a/docs/source/conf.py b/docs/source/conf.py index db44e34f4d..b25d5abbed 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -21,12 +21,14 @@ on_rtd = os.environ.get('READTHEDOCS', None) == 'True' from unittest.mock import MagicMock -MOCK_MODULES = ['numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial', - 'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.interpolate', - 'scipy.integrate', 'scipy.optimize', 'scipy.special', - 'scipy.stats', 'scipy.spatial', 'h5py', 'pandas', 'uncertainties', - 'matplotlib', 'matplotlib.pyplot','openmoc', - 'openmc.data.reconstruct'] +MOCK_MODULES = [ + 'numpy', 'numpy.polynomial', 'numpy.polynomial.polynomial', + 'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.sparse.linalg', + 'scipy.interpolate', 'scipy.integrate', 'scipy.optimize', 'scipy.special', + 'scipy.stats', 'scipy.spatial', 'h5py', 'pandas', 'uncertainties', + 'matplotlib', 'matplotlib.pyplot', 'tqdm', 'openmoc', + 'openmc.data.reconstruct' +] sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES) import numpy as np diff --git a/docs/source/pythonapi/deplete.rst b/docs/source/pythonapi/deplete.rst new file mode 100644 index 0000000000..13f2fd1550 --- /dev/null +++ b/docs/source/pythonapi/deplete.rst @@ -0,0 +1,62 @@ +.. _pythonapi_deplete: + +---------------------------------- +:mod:`openmc.deplete` -- Depletion +---------------------------------- + +Integrators +----------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myfunction.rst + + openmc.deplete.integrator.predictor + openmc.deplete.integrator.cecm + +Integrator Helper Functions +--------------------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myfunction.rst + + openmc.deplete.integrator.CRAM16 + openmc.deplete.integrator.CRAM48 + openmc.deplete.integrator.save_results + +Metaclasses +----------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + openmc.deplete.TransportOperator + +OpenMC Classes +-------------- + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + openmc.deplete.Operator + openmc.deplete.OperatorResult + +Data Classes +------------ +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + openmc.deplete.AtomNumber + openmc.deplete.Chain + openmc.deplete.Nuclide + openmc.deplete.ReactionRates + openmc.deplete.Results diff --git a/docs/source/pythonapi/deplete/index.rst b/docs/source/pythonapi/deplete/index.rst deleted file mode 100644 index f3212bd61d..0000000000 --- a/docs/source/pythonapi/deplete/index.rst +++ /dev/null @@ -1,54 +0,0 @@ -.. _api: - -================= -API Documentation -================= - -Integrators ------------ - -.. toctree:: - :maxdepth: 2 - - integrator.predictor - integrator.cecm - -Integrator Helper Functions ---------------------------- -.. toctree:: - :maxdepth: 2 - - integrator.CRAM16 - integrator.CRAM48 - integrator.save_results - -Metaclasses ------------ - -.. autosummary:: - :toctree: generated - :nosignatures: - - openmc.deplete.Operator - -OpenMC Classes --------------- - -.. autosummary:: - :toctree: generated - :nosignatures: - - openmc.deplete.Materials - openmc.deplete.OpenMCOperator - -Data Classes ------------- -.. autosummary:: - :toctree: generated - :nosignatures: - - openmc.deplete.AtomNumber - openmc.deplete.Chain - openmc.deplete.Nuclide - openmc.deplete.ReactionRates - openmc.deplete.Results diff --git a/docs/source/pythonapi/deplete/integrator.CRAM16.rst b/docs/source/pythonapi/deplete/integrator.CRAM16.rst deleted file mode 100644 index a0dc648056..0000000000 --- a/docs/source/pythonapi/deplete/integrator.CRAM16.rst +++ /dev/null @@ -1,6 +0,0 @@ -integrator\.CRAM16 -================== - -.. currentmodule:: openmc.deplete.integrator - -.. autofunction:: CRAM16 diff --git a/docs/source/pythonapi/deplete/integrator.CRAM48.rst b/docs/source/pythonapi/deplete/integrator.CRAM48.rst deleted file mode 100644 index f9720f7ad9..0000000000 --- a/docs/source/pythonapi/deplete/integrator.CRAM48.rst +++ /dev/null @@ -1,6 +0,0 @@ -integrator\.CRAM48 -================== - -.. currentmodule:: openmc.deplete.integrator - -.. autofunction:: CRAM48 diff --git a/docs/source/pythonapi/deplete/integrator.cecm.rst b/docs/source/pythonapi/deplete/integrator.cecm.rst deleted file mode 100644 index 4851b20b34..0000000000 --- a/docs/source/pythonapi/deplete/integrator.cecm.rst +++ /dev/null @@ -1,6 +0,0 @@ -integrator\.cecm -================= - -.. currentmodule:: openmc.deplete.integrator - -.. autofunction:: cecm diff --git a/docs/source/pythonapi/deplete/integrator.predictor.rst b/docs/source/pythonapi/deplete/integrator.predictor.rst deleted file mode 100644 index 2243e77f71..0000000000 --- a/docs/source/pythonapi/deplete/integrator.predictor.rst +++ /dev/null @@ -1,6 +0,0 @@ -integrator\.predictor -===================== - -.. currentmodule:: openmc.deplete.integrator - -.. autofunction:: predictor diff --git a/docs/source/pythonapi/deplete/integrator.save_results.rst b/docs/source/pythonapi/deplete/integrator.save_results.rst deleted file mode 100644 index f9c830cd5b..0000000000 --- a/docs/source/pythonapi/deplete/integrator.save_results.rst +++ /dev/null @@ -1,6 +0,0 @@ -integrator\.save_results -======================== - -.. currentmodule:: openmc.deplete.integrator - -.. autofunction:: save_results diff --git a/docs/source/pythonapi/index.rst b/docs/source/pythonapi/index.rst index 862acb2384..3c28a21852 100644 --- a/docs/source/pythonapi/index.rst +++ b/docs/source/pythonapi/index.rst @@ -15,14 +15,15 @@ there are many substantial benefits to using the Python API, including: - The ability to define dimensions using variables. - Availability of standard-library modules for working with files. - An entire ecosystem of third-party packages for scientific computing. -- Ability to create materials based on natural elements or uranium enrichment - Automated multi-group cross section generation (:mod:`openmc.mgxs`) +- A fully-featured nuclear data interface (:mod:`openmc.data`) +- Depletion capability (:mod:`openmc.deplete`) - Convenience functions (e.g., a function returning a hexagonal region) - Ability to plot individual universes as geometry is being created - A :math:`k_\text{eff}` search function (:func:`openmc.search_for_keff`) - Random sphere packing for generating TRISO particle locations (:func:`openmc.model.pack_trisos`) -- A fully-featured nuclear data interface (:mod:`openmc.data`) +- Ability to create materials based on natural elements or uranium enrichment For those new to Python, there are many good tutorials available online. We recommend going through the modules from `Codecademy @@ -45,6 +46,7 @@ Modules base model examples + deplete mgxs stats data diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 9d53f40bfd..53e71c1959 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -12,15 +12,33 @@ from abc import ABCMeta, abstractmethod from .chain import Chain OperatorResult = namedtuple('OperatorResult', ['k', 'rates']) +OperatorResult.__doc__ = """\ +Result of applying transport operator + +Parameters +---------- +k : float + Resulting eigenvalue +rates : openmc.deplete.ReactionRates + Resulting reaction rates + +""" -class Operator(metaclass=ABCMeta): +class TransportOperator(metaclass=ABCMeta): """Abstract class defining a transport operator + Each depletion integrator is written to work with a generic transport + operator that takes a vector of material compositions and returns an + eigenvalue and reaction rates. This abstract class sets the requirements for + such a transport operator. Users should instantiate + :class:`openmc.deplete.Operator` rather than this class. + Parameters ---------- chain_file : str, optional - + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. Attributes ---------- diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 9ffc3d93ec..348103ea94 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -321,9 +321,6 @@ class Chain(object): filename : str The path to the depletion chain XML file. - Todo - ---- - Allow for branching on capture, etc. """ chain = cls() diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 7d6c11190f..db58d5d527 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -8,10 +8,11 @@ from .save_results import save_results def cecm(operator, timesteps, power, print_out=True): - r"""The CE/CM integrator. + r"""Deplete using the CE/CM algorithm. - Implements the second order CE/CM Predictor-Corrector algorithm [ref]_. - This algorithm is mathematically defined as: + Implements the second order `CE/CM Predictor-Corrector algorithm + `_. This algorithm is mathematically + defined as: .. math:: y' &= A(y, t) y(t) @@ -24,17 +25,12 @@ def cecm(operator, timesteps, power, print_out=True): y_{n+1} &= \text{expm}(A_c h) y_n - .. [ref] - Isotalo, Aarno. "Comparison of Neutronics-Depletion Coupling Schemes - for Burnup Calculations-Continued Study." Nuclear Science and - Engineering 180.3 (2015): 286-300. - Parameters ---------- - operator : openmc.deplete.Operator + operator : openmc.deplete.TransportOperator The operator object to simulate on. timesteps : iterable of float - Array of timesteps in units of [s] + Array of timesteps in units of [s]. Note that values are not cumulative. power : float or iterable of float Power of the reactor in [W]. A single value indicates that the power is constant over all timesteps. An iterable indicates potentially different diff --git a/openmc/deplete/integrator/cram.py b/openmc/deplete/integrator/cram.py index 09207fbc6b..85954603a1 100644 --- a/openmc/deplete/integrator/cram.py +++ b/openmc/deplete/integrator/cram.py @@ -48,7 +48,7 @@ def deplete(chain, x, op_result, dt, print_out): # Use multiprocessing pool to distribute work with Pool() as pool: iters = zip(chains, vecs, rates, dts) - x_result = list(pool.starmap(cram_wrapper, iters)) + x_result = list(pool.starmap(_cram_wrapper, iters)) t_end = time.time() if comm.rank == 0: @@ -58,7 +58,7 @@ def deplete(chain, x, op_result, dt, print_out): return x_result -def cram_wrapper(chain, n0, rates, dt): +def _cram_wrapper(chain, n0, rates, dt): """Wraps depletion matrix creation / CRAM solve for multiprocess execution Parameters @@ -82,16 +82,11 @@ def cram_wrapper(chain, n0, rates, dt): def CRAM16(A, n0, dt): - """ Chebyshev Rational Approximation Method, order 16 + """Chebyshev Rational Approximation Method, order 16 Algorithm is the 16th order Chebyshev Rational Approximation Method, - implemented in the more stable incomplete partial fraction (IPF) form - [cram16]_. - - .. [cram16] - Pusa, Maria. "Higher-Order Chebyshev Rational Approximation Method and - Application to Burnup Equations." Nuclear Science and Engineering 182.3 - (2016). + implemented in the more stable `incomplete partial fraction (IPF) + `_ form. Parameters ---------- @@ -106,6 +101,7 @@ def CRAM16(A, n0, dt): ------- numpy.array Results of the matrix exponent. + """ alpha = np.array([+2.124853710495224e-16, @@ -144,16 +140,11 @@ def CRAM16(A, n0, dt): def CRAM48(A, n0, dt): - """ Chebyshev Rational Approximation Method, order 48 + """Chebyshev Rational Approximation Method, order 48 Algorithm is the 48th order Chebyshev Rational Approximation Method, - implemented in the more stable incomplete partial fraction (IPF) form - [cram48]_. - - .. [cram48] - Pusa, Maria. "Higher-Order Chebyshev Rational Approximation Method and - Application to Burnup Equations." Nuclear Science and Engineering 182.3 - (2016). + implemented in the more stable `incomplete partial fraction (IPF) + `_ form. Parameters ---------- @@ -168,6 +159,7 @@ def CRAM48(A, n0, dt): ------- numpy.array Results of the matrix exponent. + """ theta_r = np.array([-4.465731934165702e+1, -5.284616241568964e+0, diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 038c0778da..444ca7baa7 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -22,10 +22,10 @@ def predictor(operator, timesteps, power, print_out=True): Parameters ---------- - operator : openmc.deplete.Operator + operator : openmc.deplete.TransportOperator The operator object to simulate on. timesteps : iterable of float - Array of timesteps in units of [s] + Array of timesteps in units of [s]. Note that values are not cumulative. power : float or iterable of float Power of the reactor in [W]. A single value indicates that the power is constant over all timesteps. An iterable indicates potentially different diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index 8a0ae92040..40d2f70b63 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -9,7 +9,7 @@ def save_results(op, x, op_results, t, step_ind): Parameters ---------- - op : openmc.deplete.Operator + op : openmc.deplete.TransportOperator The operator used to generate these results. x : list of list of numpy.array The prior x vectors. Indexed [i][cell] using the above equation. diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/openmc_wrapper.py index 12ed27f229..5104ab2f17 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/openmc_wrapper.py @@ -1,6 +1,10 @@ -"""The OpenMC wrapper module. +"""OpenMC transport operator + +This module implements a transport operator for OpenMC so that it can be used by +depletion integrators. The implementation makes use of the Python bindings to +OpenMC's C API so that reading tally results and updating material number +densities is all done in-memory instead of through the filesystem. -This module implements the depletion -> OpenMC linkage. """ import copy @@ -24,7 +28,7 @@ import openmc import openmc.capi from openmc.data import JOULE_PER_EV from . import comm -from .abc import Operator, OperatorResult +from .abc import TransportOperator, OperatorResult from .atom_number import AtomNumber from .reaction_rates import ReactionRates @@ -39,8 +43,8 @@ def _distribute(items): j += chunk_size -class OpenMCOperator(Operator): - """OpenMC transport operator +class Operator(TransportOperator): + """OpenMC transport operator for depletion Parameters ---------- diff --git a/tests/dummy_geometry.py b/tests/dummy_operator.py similarity index 95% rename from tests/dummy_geometry.py rename to tests/dummy_operator.py index ca2efd6630..706793d93f 100644 --- a/tests/dummy_geometry.py +++ b/tests/dummy_operator.py @@ -1,11 +1,11 @@ import numpy as np import scipy.sparse as sp from openmc.deplete.reaction_rates import ReactionRates -from openmc.deplete.abc import Operator, OperatorResult +from openmc.deplete.abc import TransportOperator, OperatorResult -class DummyGeometry(Operator): - """This is a dummy geometry class with no statistical uncertainty. +class DummyOperator(TransportOperator): + """This is a dummy operator class with no statistical uncertainty. y_1' = sin(y_2) y_1 + cos(y_1) y_2 y_2' = -cos(y_2) y_1 + sin(y_1) y_2 diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 22125d039d..2286af908a 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -44,7 +44,7 @@ def test_full(run_in_tmpdir): # Create operator chain_file = Path(__file__).parents[2] / 'chains' / 'chain_simple.xml' - op = openmc.deplete.OpenMCOperator(geometry, settings, chain_file) + op = openmc.deplete.Operator(geometry, settings, chain_file) op.round_number = True # Power and timesteps diff --git a/tests/regression_tests/test_deplete_utilities.py b/tests/regression_tests/test_deplete_utilities.py index f38129cc79..82d4d56a4c 100644 --- a/tests/regression_tests/test_deplete_utilities.py +++ b/tests/regression_tests/test_deplete_utilities.py @@ -14,7 +14,7 @@ from openmc.deplete import utilities @pytest.fixture def res(): """Load the reference results""" - filename = str(Path(__file__).with_name('test_reference.h5')) + filename = Path(__file__).with_name('test_reference.h5') return results.read_results(filename) diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 97659b8923..6deb6cd3dd 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -8,13 +8,13 @@ import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities -from tests import dummy_geometry +from tests import dummy_operator def test_cecm(run_in_tmpdir): """Integral regression test of integrator algorithm using CE/CM.""" - op = dummy_geometry.DummyGeometry() + op = dummy_operator.DummyOperator() op.output_dir = "test_integrator_regression" # Perform simulation using the MCNPX/MCNP6 algorithm diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index 42a3c13a3a..0d283855cb 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -8,13 +8,13 @@ import openmc.deplete from openmc.deplete import results from openmc.deplete import utilities -from tests import dummy_geometry +from tests import dummy_operator def test_predictor(run_in_tmpdir): """Integral regression test of integrator algorithm using predictor/corrector""" - op = dummy_geometry.DummyGeometry() + op = dummy_operator.DummyOperator() op.output_dir = "test_integrator_regression" # Perform simulation using the predictor algorithm From c9f8daa0aba77274bdd7cf29c8c3a6ecb66970f6 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Feb 2018 23:17:50 -0600 Subject: [PATCH 148/212] Fix in ReactionRates class. More documentation updates --- openmc/deplete/__init__.py | 2 +- openmc/deplete/abc.py | 4 +- openmc/deplete/atom_number.py | 8 ++-- .../{openmc_wrapper.py => operator.py} | 26 ++++++++----- openmc/deplete/reaction_rates.py | 31 +++++++++++---- openmc/deplete/results.py | 2 +- openmc/deplete/utilities.py | 1 + tests/unit_tests/test_deplete_reaction.py | 38 +++++-------------- 8 files changed, 57 insertions(+), 55 deletions(-) rename openmc/deplete/{openmc_wrapper.py => operator.py} (98%) diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py index 2467b973a9..33b6d9af14 100644 --- a/openmc/deplete/__init__.py +++ b/openmc/deplete/__init__.py @@ -16,7 +16,7 @@ except ImportError: from .nuclide import * from .chain import * -from .openmc_wrapper import * +from .operator import * from .reaction_rates import * from .abc import * from .results import * diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 53e71c1959..f2fa736508 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -66,7 +66,7 @@ class TransportOperator(metaclass=ABCMeta): Parameters ---------- - vec : list of numpy.array + vec : list of numpy.ndarray Total atoms to be used in function. print_out : bool, optional Whether or not to print out time. @@ -108,7 +108,7 @@ class TransportOperator(metaclass=ABCMeta): Returns ------- - list of numpy.array + list of numpy.ndarray Total density for initial conditions. """ diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 1a142676cb..5179224c24 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -55,7 +55,7 @@ class AtomNumber(object): self.n_nuc_burn = n_nuc_burn - self.number = np.zeros((len(local_mats), self.n_nuc)) + self.number = np.zeros((len(local_mats), len(nuclides))) def __getitem__(self, pos): """Retrieves total atom number from AtomNumber. @@ -69,7 +69,7 @@ class AtomNumber(object): Returns ------- - numpy.array + numpy.ndarray The value indexed from self.number. """ @@ -153,7 +153,7 @@ class AtomNumber(object): Material index. nuc : str, int or slice Nuclide index. - val : numpy.array + val : numpy.ndarray Array of densities to set in [atom/cm^3] """ @@ -190,7 +190,7 @@ class AtomNumber(object): ---------- mat : str, int or slice Material index. - val : numpy.array + val : numpy.ndarray The slice to set in [atom] """ diff --git a/openmc/deplete/openmc_wrapper.py b/openmc/deplete/operator.py similarity index 98% rename from openmc/deplete/openmc_wrapper.py rename to openmc/deplete/operator.py index 5104ab2f17..af08727eaa 100644 --- a/openmc/deplete/openmc_wrapper.py +++ b/openmc/deplete/operator.py @@ -11,15 +11,8 @@ import copy from collections import OrderedDict from itertools import chain import os -import random -import sys import time -try: - import lxml.etree as ET - _have_lxml = True -except ImportError: - import xml.etree.ElementTree as ET - _have_lxml = False +import xml.etree.ElementTree as ET import h5py import numpy as np @@ -34,6 +27,19 @@ from .reaction_rates import ReactionRates def _distribute(items): + """Distribute items across MPI communicator + + Parameters + ---------- + items : list + List of items of distribute + + Returns + ------- + list + Items assigned to process that called + + """ min_size, extra = divmod(len(items), comm.size) j = 0 for i in range(comm.size): @@ -114,7 +120,7 @@ class Operator(TransportOperator): Parameters ---------- - vec : list of numpy.array + vec : list of numpy.ndarray Total atoms to be used in function. power : float Power of the reactor in [W] @@ -241,7 +247,7 @@ class Operator(TransportOperator): Returns ------- - list of numpy.array + list of numpy.ndarray Total density for initial conditions. """ diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index d1e1b0f1e2..c66003530c 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -7,14 +7,16 @@ import numpy as np class ReactionRates(np.ndarray): - """ReactionRates class. + """Reaction rates resulting from a transport operator call - An ndarray to store reaction rates with string, integer, or slice indexing. + This class is a subclass of :class:`numpy.ndarray` with a few custom + attributes that make it easy to determine what index corresponds to a given + material, nuclide, and reaction rate. Parameters ---------- - index_mat : OrderedDict of str to int - A dictionary mapping material ID as string to index. + local_mats : list of str + Material IDs nuclides : list of str Depletable nuclides index_rx : OrderedDict of str to int @@ -36,14 +38,22 @@ class ReactionRates(np.ndarray): Number of reactions. """ - def __new__(cls, index_mat, nuclides, index_rx): + + # NumPy arrays can be created 1) explicitly 2) using view casting, and 3) by + # slicing an existing array. Because of these possibilities, it's necessary + # to put initialization logic in __new__ rather than __init__. Additionally, + # subclasses need to handle the multiple ways of creating arrays by using + # the __array_finalize__ method (discussed here: + # https://docs.scipy.org/doc/numpy/user/basics.subclassing.html) + + def __new__(cls, local_mats, nuclides, index_rx): # Create appropriately-sized zeroed-out ndarray - shape = (len(index_mat), len(nuclides), len(index_rx)) + shape = (len(local_mats), len(nuclides), len(index_rx)) obj = super().__new__(cls, shape) obj[:] = 0.0 # Add mapping attributes - obj.index_mat = index_mat + obj.index_mat = {mat: i for i, mat in enumerate(local_mats)} obj.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} obj.index_rx = index_rx @@ -56,6 +66,11 @@ class ReactionRates(np.ndarray): self.index_nuc = getattr(obj, 'index_nuc', None) self.index_rx = getattr(obj, 'index_rx', None) + # Reaction rates are distributed to other processes via multiprocessing, + # which entails pickling the objects. In order to preserve the custom + # attributes, we have to modify how the ndarray is pickled as described + # here: https://stackoverflow.com/a/26599346/1572453 + def __reduce__(self): state = super().__reduce__() new_state = state[2] + (self.index_mat, self.index_nuc, self.index_rx) @@ -69,7 +84,7 @@ class ReactionRates(np.ndarray): @property def n_mat(self): - """Number of cells.""" + """Number of materials.""" return len(self.index_mat) @property diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index e18051d9d8..177158dbe2 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -42,7 +42,7 @@ class Results(object): Number of materials in entire geometry. n_stages : int Number of stages in simulation. - data : numpy.array + data : numpy.ndarray Atom quantity, stored by stage, mat, then by nuclide. """ diff --git a/openmc/deplete/utilities.py b/openmc/deplete/utilities.py index d155f321d9..59d5305465 100644 --- a/openmc/deplete/utilities.py +++ b/openmc/deplete/utilities.py @@ -38,6 +38,7 @@ def evaluate_single_nuclide(results, mat, nuc): return time, concentration + def evaluate_reaction_rate(results, mat, nuc, rx): """Return reaction rate in a single material/nuclide from a results list. diff --git a/tests/unit_tests/test_deplete_reaction.py b/tests/unit_tests/test_deplete_reaction.py index de628f8c66..e46a7b13d7 100644 --- a/tests/unit_tests/test_deplete_reaction.py +++ b/tests/unit_tests/test_deplete_reaction.py @@ -7,11 +7,11 @@ from openmc.deplete import ReactionRates def test_get_set(): """Tests the get/set methods.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1} + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235"] + react_to_ind = {"fission": 0, "(n,gamma)": 1} - rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(local_mats, nuclides, react_to_ind) assert rates.shape == (2, 2, 2) assert np.all(rates == 0.0) @@ -50,34 +50,14 @@ def test_get_set(): assert rates.get("10000", "U238", "fission") == 5.0 -def test_n_mat(): +def test_properties(): """Test number of materials property.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} + local_mats = ["10000", "10001"] + nuclides = ["U238", "U235", "Gd157"] + react_to_ind = {"fission": 0, "(n,gamma)": 1, "(n,2n)": 2, "(n,3n)": 3} - rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) + rates = ReactionRates(local_mats, nuclides, react_to_ind) assert rates.n_mat == 2 - - -def test_n_nuc(): - """Test number of nuclides property.""" - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - - rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - assert rates.n_nuc == 3 - - -def test_n_react(): - """ Test number of reactions property. """ - mat_to_ind = {"10000" : 0, "10001" : 1} - nuc_to_ind = {"U238" : 0, "U235" : 1, "Gd157" : 2} - react_to_ind = {"fission" : 0, "(n,gamma)" : 1, "(n,2n)" : 2, "(n,3n)" : 3} - - rates = ReactionRates(mat_to_ind, nuc_to_ind, react_to_ind) - assert rates.n_react == 4 From 236e7f8b9e626347eff4395508c0b95efe97493a Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 00:05:53 -0600 Subject: [PATCH 149/212] Add format spec for depletion chain XML file --- chains/chain_simple.xml | 54 +++++------ chains/chain_test.xml | 32 +++---- docs/source/io_formats/depletion_chain.rst | 102 +++++++++++++++++++++ docs/source/io_formats/index.rst | 1 + openmc/deplete/chain.py | 4 +- openmc/deplete/nuclide.py | 14 +-- tests/unit_tests/test_deplete_nuclide.py | 22 ++--- 7 files changed, 166 insertions(+), 63 deletions(-) create mode 100644 docs/source/io_formats/depletion_chain.rst diff --git a/chains/chain_simple.xml b/chains/chain_simple.xml index 345da2237d..c2e50a370f 100644 --- a/chains/chain_simple.xml +++ b/chains/chain_simple.xml @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + 2.53000e-02 @@ -25,9 +25,9 @@ 1.093250e-04 2.087260e-04 2.780820e-02 6.759540e-03 2.392300e-02 4.356330e-05 - - - + + + 2.53000e-02 @@ -35,9 +35,9 @@ 6.142710e-5 1.483250e-04 0.0292737 0.002566345 0.0219242 4.9097e-6 - - - + + + 2.53000e-02 @@ -45,5 +45,5 @@ 4.141120e-04 7.605360e-04 0.0135457 0.00026864 0.0024432 3.7100E-07 - - + + diff --git a/chains/chain_test.xml b/chains/chain_test.xml index 5985704063..c8c75ad7b3 100644 --- a/chains/chain_test.xml +++ b/chains/chain_test.xml @@ -1,17 +1,17 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + 0.0253 @@ -19,5 +19,5 @@ 0.0292737 0.002566345 - - + + diff --git a/docs/source/io_formats/depletion_chain.rst b/docs/source/io_formats/depletion_chain.rst new file mode 100644 index 0000000000..00d95bdf58 --- /dev/null +++ b/docs/source/io_formats/depletion_chain.rst @@ -0,0 +1,102 @@ +.. _io_chain: + +============================ +Depletion Chain -- chain.xml +============================ + +A depletion chain file has a ```` root element with one or more +```` child elements. The decay, reaction, and fission product data for +each nuclide appears as child elements of ````. + +--------------------- +```` Element +--------------------- + +The ```` element contains information on the decay modes, reactions, +and fission product yields for a given nuclide in the depletion chain. This +element may have the following attributes: + + :name: + Name of the nuclide + + :half_life: + Half-life of the nuclide in [s] + + :decay_modes: + Number of decay modes present + + :decay_energy: + Decay energy released in [eV] + + :reactions: + Number of reactions present + +For each decay mode, a :ref:`io_chain_decay` appears as a child of +````. For each reaction present, a :ref:`io_chain_reaction` appears as +a child of ````. If the nuclide is fissionable, a :ref:`io_chain_nfy` +appears as well. + +.. _io_chain_decay: + +------------------- +```` Element +------------------- + +The ```` element represents a single decay mode and has the following +attributes: + + :type: + The type of the decay, e.g. 'ec/beta+' + + :target: + The daughter nuclide produced from the decay + + :branching_ratio: + The branching ratio for this decay mode + +.. _io_chain_reaction: + +---------------------- +```` Element +---------------------- + +The ```` element represents a single transmutation reaction. This +element has the following attributes: + + :type: + The type of the reaction, e.g., '(n,gamma)' + + :Q: + The Q value of the reaction in [eV] + + :target: + The nuclide produced in the reaction (absent if the type is 'fission') + + :branching_ratio: + The branching ratio for the reaction + +.. _io_chain_nfy: + +------------------------------------ +```` Element +------------------------------------ + +The ```` element provides yields of fission products for +fissionable nuclides. It has the follow sub-elements: + + :energies: + Energies in [eV] at which yields for products are tabulated + + :fission_yields: + + Fission product yields for a single energy point. This element itself has a + number of attributes/sub-elements: + + :energy: + Energy in [eV] at which yields are tabulated + + :products: + Names of fission products + + :data: + Independent yields for each fission product diff --git a/docs/source/io_formats/index.rst b/docs/source/io_formats/index.rst index f3eea21def..1068973332 100644 --- a/docs/source/io_formats/index.rst +++ b/docs/source/io_formats/index.rst @@ -30,6 +30,7 @@ Data Files :maxdepth: 2 cross_sections + depletion_chain nuclear_data mgxs_library data_wmp diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 348103ea94..0cd3fb0d7e 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -327,7 +327,7 @@ class Chain(object): # Load XML tree root = ET.parse(str(filename)) - for i, nuclide_elem in enumerate(root.findall('nuclide_table')): + for i, nuclide_elem in enumerate(root.findall('nuclide')): nuc = Nuclide.from_xml(nuclide_elem) chain.nuclide_dict[nuc.name] = i @@ -350,7 +350,7 @@ class Chain(object): """ - root_elem = ET.Element('depletion') + root_elem = ET.Element('depletion_chain') for nuclide in self.nuclides: root_elem.append(nuclide.to_xml_element()) diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py index 17cf4d9b8f..4a7b86f029 100644 --- a/openmc/deplete/nuclide.py +++ b/openmc/deplete/nuclide.py @@ -23,9 +23,9 @@ class Nuclide(object): name : str Name of nuclide. half_life : float - Half life of nuclide in s^-1. + Half life of nuclide in [s]. decay_energy : float - Energy deposited from decay in eV. + Energy deposited from decay in [eV]. n_decay_modes : int Number of decay pathways. decay_modes : list of DecayTuple @@ -94,14 +94,14 @@ class Nuclide(object): nuc.decay_energy = float(element.get('decay_energy', '0')) # Check for decay paths - for decay_elem in element.iter('decay_type'): + for decay_elem in element.iter('decay'): d_type = decay_elem.get('type') target = decay_elem.get('target') branching_ratio = float(decay_elem.get('branching_ratio')) nuc.decay_modes.append(DecayTuple(d_type, target, branching_ratio)) # Check for reaction paths - for reaction_elem in element.iter('reaction_type'): + for reaction_elem in element.iter('reaction'): r_type = reaction_elem.get('type') Q = float(reaction_elem.get('Q', '0')) branching_ratio = float(reaction_elem.get('branching_ratio', '1')) @@ -138,7 +138,7 @@ class Nuclide(object): XML element to write nuclide data to """ - elem = ET.Element('nuclide_table') + elem = ET.Element('nuclide') elem.set('name', self.name) if self.half_life is not None: @@ -146,14 +146,14 @@ class Nuclide(object): elem.set('decay_modes', str(len(self.decay_modes))) elem.set('decay_energy', str(self.decay_energy)) for mode, daughter, br in self.decay_modes: - mode_elem = ET.SubElement(elem, 'decay_type') + mode_elem = ET.SubElement(elem, 'decay') mode_elem.set('type', mode) mode_elem.set('target', daughter) mode_elem.set('branching_ratio', str(br)) elem.set('reactions', str(len(self.reactions))) for rx, daughter, Q, br in self.reactions: - rx_elem = ET.SubElement(elem, 'reaction_type') + rx_elem = ET.SubElement(elem, 'reaction') rx_elem.set('type', rx) rx_elem.set('Q', str(Q)) if rx != 'fission': diff --git a/tests/unit_tests/test_deplete_nuclide.py b/tests/unit_tests/test_deplete_nuclide.py index 2add13f866..f2a101d2a9 100644 --- a/tests/unit_tests/test_deplete_nuclide.py +++ b/tests/unit_tests/test_deplete_nuclide.py @@ -37,14 +37,14 @@ def test_from_xml(): """Test reading nuclide data from an XML element.""" data = """ - - - - - - - - + + + + + + + + 0.0253 @@ -52,7 +52,7 @@ def test_from_xml(): 0.062155 0.0497641 0.0481413 - + """ element = ET.fromstring(data) @@ -96,7 +96,7 @@ def test_to_xml_element(): assert element.get("half_life") == "0.123" - decay_elems = element.findall("decay_type") + decay_elems = element.findall("decay") assert len(decay_elems) == 2 assert decay_elems[0].get("type") == "beta-" assert decay_elems[0].get("target") == "B" @@ -105,7 +105,7 @@ def test_to_xml_element(): assert decay_elems[1].get("target") == "D" assert decay_elems[1].get("branching_ratio") == "0.01" - rx_elems = element.findall("reaction_type") + rx_elems = element.findall("reaction") assert len(rx_elems) == 2 assert rx_elems[0].get("type") == "fission" assert float(rx_elems[0].get("Q")) == 2.0e8 From f3758e5330490e4f90df99938bb76efd2e9cebb6 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 07:41:50 -0600 Subject: [PATCH 150/212] Fix broken tests on Py3.4, 3.5 --- openmc/deplete/atom_number.py | 5 +++-- openmc/deplete/integrator/save_results.py | 4 ++-- openmc/deplete/operator.py | 3 +-- openmc/deplete/reaction_rates.py | 11 ++++++----- openmc/deplete/results.py | 21 ++++++++------------- tests/unit_tests/test_deplete_chain.py | 7 +++---- tests/unit_tests/test_deplete_integrator.py | 21 +++++++++------------ tests/unit_tests/test_deplete_reaction.py | 8 ++++---- 8 files changed, 36 insertions(+), 44 deletions(-) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 5179224c24..8f6a419113 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -2,6 +2,7 @@ An ndarray to store atom densities with string, integer, or slice indexing. """ +from collections import OrderedDict import numpy as np @@ -44,8 +45,8 @@ class AtomNumber(object): """ def __init__(self, local_mats, nuclides, volume, n_nuc_burn): - self.index_mat = {mat: i for i, mat in enumerate(local_mats)} - self.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} + self.index_mat = OrderedDict((mat, i) for i, mat in enumerate(local_mats)) + self.index_nuc = OrderedDict((nuc, i) for i, nuc in enumerate(nuclides)) self.volume = np.ones(len(local_mats)) for mat, val in volume.items(): diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py index 40d2f70b63..98245fdeae 100644 --- a/openmc/deplete/integrator/save_results.py +++ b/openmc/deplete/integrator/save_results.py @@ -22,12 +22,12 @@ def save_results(op, x, op_results, t, step_ind): """ # Get indexing terms - vol_list, nuc_list, burn_list, full_burn_list = op.get_results_info() + vol_dict, nuc_list, burn_list, full_burn_list = op.get_results_info() # Create results stages = len(x) results = Results() - results.allocate(vol_list, nuc_list, burn_list, full_burn_list, stages) + results.allocate(vol_dict, nuc_list, burn_list, full_burn_list, stages) n_mat = len(burn_list) diff --git a/openmc/deplete/operator.py b/openmc/deplete/operator.py index af08727eaa..d0a64a06d3 100644 --- a/openmc/deplete/operator.py +++ b/openmc/deplete/operator.py @@ -111,9 +111,8 @@ class Operator(TransportOperator): self._extract_number(self.local_mats, volume, nuclides) # Create reaction rates array - index_rx = {rx: i for i, rx in enumerate(self.chain.reactions)} self.reaction_rates = ReactionRates( - self.local_mats, self._burnable_nucs, index_rx) + self.local_mats, self._burnable_nucs, self.chain.reactions) def __call__(self, vec, power, print_out=True): """Runs a simulation. diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index c66003530c..482c357a29 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -2,6 +2,7 @@ An ndarray to store reaction rates with string, integer, or slice indexing. """ +from collections import OrderedDict import numpy as np @@ -19,8 +20,8 @@ class ReactionRates(np.ndarray): Material IDs nuclides : list of str Depletable nuclides - index_rx : OrderedDict of str to int - A dictionary mapping reaction name as string to index. + reactions : list of str + Transmutation reactions being tracked Attributes ---------- @@ -46,16 +47,16 @@ class ReactionRates(np.ndarray): # the __array_finalize__ method (discussed here: # https://docs.scipy.org/doc/numpy/user/basics.subclassing.html) - def __new__(cls, local_mats, nuclides, index_rx): + def __new__(cls, local_mats, nuclides, reactions): # Create appropriately-sized zeroed-out ndarray - shape = (len(local_mats), len(nuclides), len(index_rx)) + shape = (len(local_mats), len(nuclides), len(reactions)) obj = super().__new__(cls, shape) obj[:] = 0.0 # Add mapping attributes obj.index_mat = {mat: i for i, mat in enumerate(local_mats)} obj.index_nuc = {nuc: i for i, nuc in enumerate(nuclides)} - obj.index_rx = index_rx + obj.index_rx = {rx: i for i, rx in enumerate(reactions)} return obj diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 177158dbe2..307d18a405 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -76,16 +76,10 @@ class Results(object): """ self.volume = copy.deepcopy(volume) - self.nuc_to_ind = OrderedDict() - self.mat_to_ind = OrderedDict() + self.nuc_to_ind = {nuc: i for i, nuc in enumerate(nuc_list)} + self.mat_to_ind = {mat: i for i, mat in enumerate(burn_list)} self.mat_to_hdf5_ind = {mat: i for i, mat in enumerate(full_burn_list)} - for i, mat in enumerate(burn_list): - self.mat_to_ind[mat] = i - - for i, nuc in enumerate(nuc_list): - self.nuc_to_ind[nuc] = i - # Create storage array self.data = np.zeros((stages, self.n_mat, self.n_nuc)) @@ -123,8 +117,8 @@ class Results(object): ------- float The atoms for stage, mat, nuc - """ + """ stage, mat, nuc = pos if isinstance(mat, str): mat = self.mat_to_ind[mat] @@ -145,8 +139,8 @@ class Results(object): val : float The value to set data to. - """ + """ stage, mat, nuc = pos if isinstance(mat, str): mat = self.mat_to_ind[mat] @@ -162,8 +156,8 @@ class Results(object): ---------- handle : h5py.File or h5py.Group An hdf5 file or group type to store this in. - """ + """ # Create and save the 5 dictionaries: # quantities # self.mat_to_ind -> self.volume (TODO: support for changing volumes) @@ -234,8 +228,8 @@ class Results(object): An hdf5 file or group type to store this in. index : int What step is this? - """ + """ if "/number" not in handle: comm.barrier() self.create_hdf5(handle) @@ -299,6 +293,7 @@ class Results(object): An hdf5 file or group type to load from. index : int What step is this? + """ results = cls() @@ -357,8 +352,8 @@ def write_results(result, filename, index): Target filename. index : int What step is this? - """ + """ if have_mpi and h5py.get_config().mpi: kwargs = {'driver': 'mpio', 'comm': comm} else: diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index ae900e62d7..7ac3e2f8dd 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -136,11 +136,10 @@ def test_form_matrix(): chain = Chain.from_xml(_test_filename) - mat_ind = {"10000": 0, "10001": 1} - nuc_ind = {"A": 0, "B": 1, "C": 2} - react_ind = {rx: i for i, rx in enumerate(chain.reactions)} + mats = ["10000", "10001"] + nuclides = ["A", "B", "C"] - react = reaction_rates.ReactionRates(mat_ind, nuc_ind, react_ind) + react = reaction_rates.ReactionRates(mats, nuclides, chain.reactions) react.set("10000", "C", "fission", 1.0) react.set("10000", "A", "(n,gamma)", 2.0) diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index 78dd6bcef2..b209900889 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -26,20 +26,18 @@ def test_save_results(run_in_tmpdir): op = MagicMock() vol_dict = {} - full_burn_dict = {} + full_burn_list = [] - j = 0 for i in range(comm.size): vol_dict[str(2*i)] = 1.2 vol_dict[str(2*i + 1)] = 1.2 - full_burn_dict[str(2*i)] = j - full_burn_dict[str(2*i + 1)] = j + 1 - j += 2 + full_burn_list.append(str(2*i)) + full_burn_list.append(str(2*i + 1)) - burn_list = [str(i) for i in range(2*comm.rank, 2*comm.rank + 2)] + burn_list = full_burn_list[2*comm.rank : 2*comm.rank + 2] nuc_list = ["na", "nb"] - op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_dict + op.get_results_info.return_value = vol_dict, nuc_list, burn_list, full_burn_list # Construct x x1 = [] @@ -50,18 +48,17 @@ def test_save_results(run_in_tmpdir): x2.append([np.random.rand(2), np.random.rand(2)]) # Construct r - cell_dict = {s: i for i, s in enumerate(burn_list)} - r1 = ReactionRates(cell_dict, {"na": 0, "nb": 1}, {"ra": 0, "rb": 1}) - r1.rates = np.random.rand(2, 2, 2) + r1 = ReactionRates(burn_list, ["na", "nb"], ["ra", "rb"]) + r1[:] = np.random.rand(2, 2, 2) rate1 = [] rate2 = [] for i in range(stages): rate1.append(copy.deepcopy(r1)) - r1.rates = np.random.rand(2, 2, 2) + r1[:] = np.random.rand(2, 2, 2) rate2.append(copy.deepcopy(r1)) - r1.rates = np.random.rand(2, 2, 2) + r1[:] = np.random.rand(2, 2, 2) # Create global terms eigvl1 = np.random.rand(stages) diff --git a/tests/unit_tests/test_deplete_reaction.py b/tests/unit_tests/test_deplete_reaction.py index e46a7b13d7..18639a27a1 100644 --- a/tests/unit_tests/test_deplete_reaction.py +++ b/tests/unit_tests/test_deplete_reaction.py @@ -9,9 +9,9 @@ def test_get_set(): local_mats = ["10000", "10001"] nuclides = ["U238", "U235"] - react_to_ind = {"fission": 0, "(n,gamma)": 1} + reactions = ["fission", "(n,gamma)"] - rates = ReactionRates(local_mats, nuclides, react_to_ind) + rates = ReactionRates(local_mats, nuclides, reactions) assert rates.shape == (2, 2, 2) assert np.all(rates == 0.0) @@ -54,9 +54,9 @@ def test_properties(): """Test number of materials property.""" local_mats = ["10000", "10001"] nuclides = ["U238", "U235", "Gd157"] - react_to_ind = {"fission": 0, "(n,gamma)": 1, "(n,2n)": 2, "(n,3n)": 3} + reactions = ["fission", "(n,gamma)", "(n,2n)", "(n,3n)"] - rates = ReactionRates(local_mats, nuclides, react_to_ind) + rates = ReactionRates(local_mats, nuclides, reactions) assert rates.n_mat == 2 assert rates.n_nuc == 3 From 4aae63ff770d9db1d70b175ada41e24a867b3737 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Tue, 20 Feb 2018 14:38:45 -0500 Subject: [PATCH 151/212] Reorder printing calls to output CMFD data correctly --- src/output.F90 | 16 ++++++++++++---- src/simulation.F90 | 4 +++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/output.F90 b/src/output.F90 index 9a144721dc..11366b5c03 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -368,7 +368,7 @@ contains ! write out entropy info if (entropy_on) write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5)', ADVANCE='NO') & entropy % data(i) - + ! write out accumulated k-effective if after first active batch if (n > 1) then write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5," +/-",F8.5)', ADVANCE='NO') & @@ -376,6 +376,15 @@ contains else write(UNIT=OUTPUT_UNIT, FMT='(23X)', ADVANCE='NO') end if + + end subroutine print_batch_keff + +!=============================================================================== +! PRINT_BATCH_KEFF displays the last batch's tallied value of the neutron +! multiplication factor as well as the average value if we're in active batches +!=============================================================================== + + subroutine print_cmfd() ! write out cmfd keff if it is active and other display info if (cmfd_on) then @@ -396,11 +405,10 @@ contains cmfd % dom(current_batch) end select end if - ! next line write(UNIT=OUTPUT_UNIT, FMT=*) - - end subroutine print_batch_keff + + end subroutine print_cmfd !=============================================================================== ! PRINT_PLOT displays selected options for plotting diff --git a/src/simulation.F90 b/src/simulation.F90 index ef29e7832b..91c176b995 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -24,7 +24,8 @@ module simulation use nuclide_header, only: micro_xs, n_nuclides use output, only: header, print_columns, & print_batch_keff, print_generation, print_runtime, & - print_results, print_overlap_check, write_tallies + print_results, print_overlap_check, write_tallies, & + print_cmfd use particle_header, only: Particle use random_lcg, only: set_particle_seed use settings @@ -338,6 +339,7 @@ contains if (run_mode == MODE_EIGENVALUE) then ! Perform CMFD calculation if on if (cmfd_on) call execute_cmfd() + call print_cmfd() end if ! Check_triggers From 552a8b9c0c48adb124a79405c62bbaa66c849fc9 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Tue, 20 Feb 2018 14:46:03 -0500 Subject: [PATCH 152/212] Add description of print_cmfd --- src/output.F90 | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/output.F90 b/src/output.F90 index 11366b5c03..30219e98a2 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -368,7 +368,7 @@ contains ! write out entropy info if (entropy_on) write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5)', ADVANCE='NO') & entropy % data(i) - + ! write out accumulated k-effective if after first active batch if (n > 1) then write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5," +/-",F8.5)', ADVANCE='NO') & @@ -380,8 +380,9 @@ contains end subroutine print_batch_keff !=============================================================================== -! PRINT_BATCH_KEFF displays the last batch's tallied value of the neutron -! multiplication factor as well as the average value if we're in active batches +! PRINT_CMFD displays the CMFD related information to output after CMFD is +! executed. Will print blank line if CMFD is not on, to ensure consistent +! formatting of output columns !=============================================================================== subroutine print_cmfd() @@ -405,9 +406,10 @@ contains cmfd % dom(current_batch) end select end if + ! next line write(UNIT=OUTPUT_UNIT, FMT=*) - + end subroutine print_cmfd !=============================================================================== From f15f824c997aa214d11fb1efc85dc0604a17bcd6 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Tue, 20 Feb 2018 14:48:36 -0500 Subject: [PATCH 153/212] Minor spacing fix --- src/output.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/output.F90 b/src/output.F90 index 30219e98a2..643a28b671 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -409,7 +409,7 @@ contains ! next line write(UNIT=OUTPUT_UNIT, FMT=*) - + end subroutine print_cmfd !=============================================================================== From 6fac1367ec15fc6ee45fcfd220be2205de2b5f88 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 14:43:26 -0600 Subject: [PATCH 154/212] Improve depletion reference documentation --- docs/source/conf.py | 1 + docs/source/pythonapi/deplete.rst | 98 +++++++++++++++++-------------- openmc/deplete/abc.py | 2 + openmc/deplete/atom_number.py | 2 - openmc/deplete/chain.py | 7 +++ openmc/deplete/integrator/cecm.py | 2 +- openmc/deplete/nuclide.py | 50 +++++++++++++--- openmc/deplete/operator.py | 7 ++- openmc/deplete/reaction_rates.py | 3 - openmc/deplete/results.py | 86 +++++++++++++-------------- 10 files changed, 155 insertions(+), 103 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index b25d5abbed..a2fec39b75 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -32,6 +32,7 @@ MOCK_MODULES = [ sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES) import numpy as np +np.ndarray = MagicMock np.polynomial.Polynomial = MagicMock diff --git a/docs/source/pythonapi/deplete.rst b/docs/source/pythonapi/deplete.rst index 13f2fd1550..1d1a1c0ee5 100644 --- a/docs/source/pythonapi/deplete.rst +++ b/docs/source/pythonapi/deplete.rst @@ -4,59 +4,71 @@ :mod:`openmc.deplete` -- Depletion ---------------------------------- -Integrators ------------ +.. module:: openmc.deplete + +Two functions are provided that implement different time-integration algorithms +for depletion calculations. .. autosummary:: :toctree: generated :nosignatures: :template: myfunction.rst - openmc.deplete.integrator.predictor - openmc.deplete.integrator.cecm + integrator.predictor + integrator.cecm -Integrator Helper Functions ---------------------------- +Each of these functions expects a "transport operator" to be passed. An operator +specific to OpenMC is available using the following class: + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + Operator + +Internal Classes and Functions +------------------------------ + +During a depletion calculation, the depletion chain, reaction rates, and number +densities are managed through a series of internal classes that are not normally +visible to a user. However, should you find yourself wondering about these +classes (e.g., if you want to know what decay modes or reactions are present in +a depletion chain), they are documented here. The following classes store data +for a depletion chain: + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + Chain + DecayTuple + Nuclide + ReactionTuple + +The following classes are used during a depletion simulation and store auxiliary +data, such as number densities and reaction rates for each material. + +.. autosummary:: + :toctree: generated + :nosignatures: + :template: myclass.rst + + AtomNumber + OperatorResult + ReactionRates + Results + TransportOperator + +Each of the integrator functions also relies on a number of "helper" functions +as follows: .. autosummary:: :toctree: generated :nosignatures: :template: myfunction.rst - openmc.deplete.integrator.CRAM16 - openmc.deplete.integrator.CRAM48 - openmc.deplete.integrator.save_results - -Metaclasses ------------ - -.. autosummary:: - :toctree: generated - :nosignatures: - :template: myclass.rst - - openmc.deplete.TransportOperator - -OpenMC Classes --------------- - -.. autosummary:: - :toctree: generated - :nosignatures: - :template: myclass.rst - - openmc.deplete.Operator - openmc.deplete.OperatorResult - -Data Classes ------------- -.. autosummary:: - :toctree: generated - :nosignatures: - :template: myclass.rst - - openmc.deplete.AtomNumber - openmc.deplete.Chain - openmc.deplete.Nuclide - openmc.deplete.ReactionRates - openmc.deplete.Results + integrator.CRAM16 + integrator.CRAM48 + integrator.save_results diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index f2fa736508..8b42ee800e 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -23,6 +23,8 @@ rates : openmc.deplete.ReactionRates Resulting reaction rates """ +OperatorResult.k.__doc__ = None +OperatorResult.rates.__doc__ = None class TransportOperator(metaclass=ABCMeta): diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 8f6a419113..9a32dfa3a0 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -113,12 +113,10 @@ class AtomNumber(object): @property def n_nuc(self): - """Number of nuclides.""" return len(self.index_nuc) @property def burnable_nuclides(self): - """All burnable nuclide names. Used for sorting the simulation.""" return [nuc for nuc, ind in self.index_nuc.items() if ind < self.n_nuc_burn] diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 0cd3fb0d7e..23395329eb 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -111,6 +111,13 @@ def replace_missing(product, decay_data): class Chain(object): """Full representation of a depletion chain. + A depletion chain can be created by using the :meth:`from_endf` method which + requires a list of ENDF incident neutron, decay, and neutron fission product + yield sublibrary files. The depletion chain used during a depletion + simulation is indicated by either an argument to + :class:`openmc.deplete.Operator` or through the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable. + Attributes ---------- nuclides : list of openmc.deplete.Nuclide diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index db58d5d527..9a07cd198f 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -10,7 +10,7 @@ from .save_results import save_results def cecm(operator, timesteps, power, print_out=True): r"""Deplete using the CE/CM algorithm. - Implements the second order `CE/CM Predictor-Corrector algorithm + Implements the second order `CE/CM predictor-corrector algorithm `_. This algorithm is mathematically defined as: diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py index 4a7b86f029..af10e5c2f9 100644 --- a/openmc/deplete/nuclide.py +++ b/openmc/deplete/nuclide.py @@ -9,14 +9,50 @@ try: except ImportError: import xml.etree.ElementTree as ET + DecayTuple = namedtuple('DecayTuple', 'type target branching_ratio') +DecayTuple.__doc__ = """\ +Decay mode information + +Parameters +---------- +type : str + Type of the decay mode, e.g., 'beta-' +target : str + Nuclide resulting from decay +branching_ratio : float + Branching ratio of the decay mode + +""" +DecayTuple.type.__doc__ = None +DecayTuple.target.__doc__ = None +DecayTuple.branching_ratio.__doc__ = None + + ReactionTuple = namedtuple('ReactionTuple', 'type target Q branching_ratio') +ReactionTuple.__doc__ = """\ +Transmutation reaction information + +Parameters +---------- +type : str + Type of the reaction, e.g., 'fission' +target : str + nuclide resulting from reaction +Q : float + Q value of the reaction in [eV] +branching_ratio : float + Branching ratio of the reaction + +""" +ReactionTuple.type.__doc__ = None +ReactionTuple.target.__doc__ = None +ReactionTuple.Q.__doc__ = None +ReactionTuple.branching_ratio.__doc__ = None class Nuclide(object): - """The Nuclide class. - - Contains everything in a depletion chain relating to a single nuclide. + """Decay modes, reactions, and fission yields for a single nuclide. Attributes ---------- @@ -28,12 +64,12 @@ class Nuclide(object): Energy deposited from decay in [eV]. n_decay_modes : int Number of decay pathways. - decay_modes : list of DecayTuple + decay_modes : list of openmc.deplete.DecayTuple Decay mode information. Each element of the list is a named tuple with attributes 'type', 'target', and 'branching_ratio'. n_reaction_paths : int Number of possible reaction pathways. - reactions : list of ReactionTuple + reactions : list of openmc.deplete.ReactionTuple Reaction information. Each element of the list is a named tuple with attribute 'type', 'target', 'Q', and 'branching_ratio'. yield_data : dict of float to list @@ -62,12 +98,10 @@ class Nuclide(object): @property def n_decay_modes(self): - """Number of decay modes.""" return len(self.decay_modes) @property def n_reaction_paths(self): - """Number of possible reaction pathways.""" return len(self.reactions) @classmethod @@ -81,7 +115,7 @@ class Nuclide(object): Returns ------- - nuc : Nuclide + nuc : openmc.deplete.Nuclide Instance of a nuclide """ diff --git a/openmc/deplete/operator.py b/openmc/deplete/operator.py index d0a64a06d3..1c62bdd401 100644 --- a/openmc/deplete/operator.py +++ b/openmc/deplete/operator.py @@ -50,7 +50,12 @@ def _distribute(items): class Operator(TransportOperator): - """OpenMC transport operator for depletion + """OpenMC transport operator for depletion. + + Instances of this class can be used to perform depletion using OpenMC as the + transport operator. Normally, a user needn't call methods of this class + directly. Instead, an instance of this class is passed to an integrator + function, such as :func:`openmc.deplete.integrator.cecm`. Parameters ---------- diff --git a/openmc/deplete/reaction_rates.py b/openmc/deplete/reaction_rates.py index 482c357a29..fddb88b19d 100644 --- a/openmc/deplete/reaction_rates.py +++ b/openmc/deplete/reaction_rates.py @@ -85,17 +85,14 @@ class ReactionRates(np.ndarray): @property def n_mat(self): - """Number of materials.""" return len(self.index_mat) @property def n_nuc(self): - """Number of nucs.""" return len(self.index_nuc) @property def n_react(self): - """Number of reactions.""" return len(self.index_rx) def get(self, mat, nuc, rx): diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index 307d18a405..f27353a4e3 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -58,51 +58,6 @@ class Results(object): self.data = None - def allocate(self, volume, nuc_list, burn_list, full_burn_list, stages): - """Allocates memory of Results. - - Parameters - ---------- - volume : dict of str float - Volumes corresponding to materials in full_burn_dict - nuc_list : list of str - A list of all nuclide names. Used for sorting the simulation. - burn_list : list of int - A list of all mat IDs to be burned. Used for sorting the simulation. - full_burn_list : list of str - List of all burnable material IDs - stages : int - Number of stages in simulation. - - """ - self.volume = copy.deepcopy(volume) - self.nuc_to_ind = {nuc: i for i, nuc in enumerate(nuc_list)} - self.mat_to_ind = {mat: i for i, mat in enumerate(burn_list)} - self.mat_to_hdf5_ind = {mat: i for i, mat in enumerate(full_burn_list)} - - # Create storage array - self.data = np.zeros((stages, self.n_mat, self.n_nuc)) - - @property - def n_mat(self): - """Number of mats.""" - return len(self.mat_to_ind) - - @property - def n_nuc(self): - """Number of nuclides.""" - return len(self.nuc_to_ind) - - @property - def n_hdf5_mats(self): - """Number of materials in entire geometry.""" - return len(self.mat_to_hdf5_ind) - - @property - def n_stages(self): - """Number of stages in simulation.""" - return self.data.shape[0] - def __getitem__(self, pos): """Retrieves an item from results. @@ -149,6 +104,47 @@ class Results(object): self.data[stage, mat, nuc] = val + @property + def n_mat(self): + return len(self.mat_to_ind) + + @property + def n_nuc(self): + return len(self.nuc_to_ind) + + @property + def n_hdf5_mats(self): + return len(self.mat_to_hdf5_ind) + + @property + def n_stages(self): + return self.data.shape[0] + + def allocate(self, volume, nuc_list, burn_list, full_burn_list, stages): + """Allocates memory of Results. + + Parameters + ---------- + volume : dict of str float + Volumes corresponding to materials in full_burn_dict + nuc_list : list of str + A list of all nuclide names. Used for sorting the simulation. + burn_list : list of int + A list of all mat IDs to be burned. Used for sorting the simulation. + full_burn_list : list of str + List of all burnable material IDs + stages : int + Number of stages in simulation. + + """ + self.volume = copy.deepcopy(volume) + self.nuc_to_ind = {nuc: i for i, nuc in enumerate(nuc_list)} + self.mat_to_ind = {mat: i for i, mat in enumerate(burn_list)} + self.mat_to_hdf5_ind = {mat: i for i, mat in enumerate(full_burn_list)} + + # Create storage array + self.data = np.zeros((stages, self.n_mat, self.n_nuc)) + def create_hdf5(self, handle): """Creates file structure for a blank HDF5 file. From 33dec88bd089876b36a73d0850ee594e1a7a49d6 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 15:35:39 -0600 Subject: [PATCH 155/212] Add format spec for depletion results HDF5 file (add necessary attributes too) --- docs/source/io_formats/depletion_chain.rst | 2 +- docs/source/io_formats/depletion_results.rst | 42 ++++++++++++++++++ docs/source/io_formats/index.rst | 7 +-- openmc/checkvalue.py | 4 +- openmc/deplete/results.py | 44 ++++++++++--------- tests/regression_tests/test_reference.h5 | Bin 162120 -> 162320 bytes 6 files changed, 72 insertions(+), 27 deletions(-) create mode 100644 docs/source/io_formats/depletion_results.rst diff --git a/docs/source/io_formats/depletion_chain.rst b/docs/source/io_formats/depletion_chain.rst index 00d95bdf58..b0dd72eb9a 100644 --- a/docs/source/io_formats/depletion_chain.rst +++ b/docs/source/io_formats/depletion_chain.rst @@ -1,4 +1,4 @@ -.. _io_chain: +.. _io_depletion_chain: ============================ Depletion Chain -- chain.xml diff --git a/docs/source/io_formats/depletion_results.rst b/docs/source/io_formats/depletion_results.rst new file mode 100644 index 0000000000..fcbc4fb99b --- /dev/null +++ b/docs/source/io_formats/depletion_results.rst @@ -0,0 +1,42 @@ +.. _io_depletion_results: + +============================= +Depletion Results File Format +============================= + +The current version of the depletion results file format is 1.0. + +**/** + +:Attributes: - **filetype** (*char[]*) -- String indicating the type of file. + - **version** (*int[2]*) -- Major and minor version of the + statepoint file format. + +:Datasets: - **eigenvalues** (*float[][]*) -- k-eigenvalues at each + time/stage. This array has shape (number of timesteps, number of + stages). + - **number** (*float[][][][]*) -- Total number of atoms. This array + has shape (number of timesteps, number of stages, number of + materials, number of nuclides). + - **reaction rates** (*float[][][][][]*) -- Reaction rates used to + build depletion matrices. This array has shape (number of + timesteps, number of stages, number of materials, number of + nuclides, number of reactions). + - **time** (*float[][2]*) -- Time in [s] at beginning/end of each + step. + +**/materials//** + +:Attributes: - **index** (*int*) -- Index used in results for this material + - **volume** (*float*) -- Volume of this material in [cm^3] + +**/nuclides//** + +:Attributes: - **atom number index** (*int*) -- Index in array of total atoms + for this nuclide + - **reaction rate index** (*int*) -- Index in array of reaction + rates for this nuclide + +**/reactions//** + +:Attributes: - **index** (*int*) -- Index user in results for this reaction diff --git a/docs/source/io_formats/index.rst b/docs/source/io_formats/index.rst index 1068973332..c1bb76a29a 100644 --- a/docs/source/io_formats/index.rst +++ b/docs/source/io_formats/index.rst @@ -12,7 +12,7 @@ Input Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 geometry materials @@ -27,7 +27,7 @@ Data Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 cross_sections depletion_chain @@ -42,11 +42,12 @@ Output Files .. toctree:: :numbered: - :maxdepth: 2 + :maxdepth: 1 statepoint source summary + depletion_results particle_restart track voxel diff --git a/openmc/checkvalue.py b/openmc/checkvalue.py index dd32aa566c..2f80ee4c0c 100644 --- a/openmc/checkvalue.py +++ b/openmc/checkvalue.py @@ -246,9 +246,9 @@ def check_filetype_version(obj, expected_type, expected_version): ---------- obj : h5py.File HDF5 file to check - expected_type + expected_type : str Expected file type, e.g. 'statepoint' - expected_version + expected_version : int Expected major version number. """ diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index f27353a4e3..b7e5623c7d 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -11,12 +11,13 @@ import h5py from . import comm, have_mpi from .reaction_rates import ReactionRates +from openmc.checkvalue import check_filetype_version -RESULTS_VERSION = 2 +_VERSION_RESULTS = (1, 0) class Results(object): - """Contains output of a depletion run. + """Output of a depletion run Attributes ---------- @@ -145,8 +146,8 @@ class Results(object): # Create storage array self.data = np.zeros((stages, self.n_mat, self.n_nuc)) - def create_hdf5(self, handle): - """Creates file structure for a blank HDF5 file. + def _write_hdf5_metadata(self, handle): + """Writes result metadata in HDF5 file Parameters ---------- @@ -165,7 +166,8 @@ class Results(object): # Store concentration mat and nuclide dictionaries (along with volumes) - handle.create_dataset("version", data=RESULTS_VERSION) + handle.attrs['version'] = np.array(_VERSION_RESULTS) + handle.attrs['filetype'] = np.string_('depletion results') mat_list = sorted(self.mat_to_hdf5_ind, key=int) nuc_list = sorted(self.nuc_to_ind) @@ -221,14 +223,14 @@ class Results(object): Parameters ---------- handle : h5py.File or h5py.Group - An hdf5 file or group type to store this in. + An HDF5 file or group type to store this in. index : int What step is this? """ if "/number" not in handle: comm.barrier() - self.create_hdf5(handle) + self._write_hdf5_metadata(handle) comm.barrier() @@ -280,14 +282,14 @@ class Results(object): time_dset[index, :] = self.time @classmethod - def from_hdf5(cls, handle, index): + def from_hdf5(cls, handle, step): """Loads results object from HDF5. Parameters ---------- handle : h5py.File or h5py.Group - An hdf5 file or group type to load from. - index : int + An HDF5 file or group type to load from. + step : int What step is this? """ @@ -298,9 +300,9 @@ class Results(object): eigenvalues_dset = handle["/eigenvalues"] time_dset = handle["/time"] - results.data = number_dset[index, :, :, :] - results.k = eigenvalues_dset[index, :] - results.time = time_dset[index, :] + results.data = number_dset[step, :, :, :] + results.k = eigenvalues_dset[step, :] + results.time = time_dset[step, :] # Reconstruct dictionaries results.volume = OrderedDict() @@ -331,14 +333,14 @@ class Results(object): for i in range(results.n_stages): rate = ReactionRates(results.mat_to_ind, rxn_nuc_to_ind, rxn_to_ind) - rate[:] = handle["/reaction rates"][index, i, :, :, :] + rate[:] = handle["/reaction rates"][step, i, :, :, :] results.rates.append(rate) return results -def write_results(result, filename, index): - """Outputs result to an .hdf5 file. +def write_results(result, filename, step): + """Outputs result to an HDF5 file. Parameters ---------- @@ -346,7 +348,7 @@ def write_results(result, filename, index): Object to be stored in a file. filename : String Target filename. - index : int + step : int What step is this? """ @@ -355,10 +357,10 @@ def write_results(result, filename, index): else: kwargs = {} - kwargs['mode'] = "w" if index == 0 else "a" + kwargs['mode'] = "w" if step == 0 else "a" with h5py.File(filename, **kwargs) as handle: - result.to_hdf5(handle, index) + result.to_hdf5(handle, step) def read_results(filename): @@ -371,12 +373,12 @@ def read_results(filename): Returns ------- - results : list of Results + results : list of openmc.deplete.Results The result objects. """ with h5py.File(str(filename), "r") as fh: - assert fh["version"].value == RESULTS_VERSION + check_filetype_version(fh, 'depletion results', _VERSION_RESULTS[0]) # Get number of results stored n = fh["number"].value.shape[0] diff --git a/tests/regression_tests/test_reference.h5 b/tests/regression_tests/test_reference.h5 index 6e724c597107560c4155a257f4e854210f36f08e..5323a9a904e0fce1f806fbc49ad90324b4fe1aa9 100644 GIT binary patch delta 188 zcmX@{iF3ji&IuY!0#y^WEG9o<7vuD(WMTk;6VqQhGpaYPXkEd$bp_LciirghmOKm| z3@ku7Mg|TB9tH`9vecsD%=|nC0S*SB2naZUNk&FSFby$@fq`lI#X?4LZyumDL^~%? zIR`^pW=?8JWkD)fEszif>JkLf5X}q>DX9fO1wacFic*V9b4rR~3K;|@ZWILo?m{Cr delta 45 xcmbR6h4aKG&IuY!9+eZdET$_dGKz6^FhIZxrs=Po8PytBw60*>x`Jsz1prXj4y6D9 From 4a500df455aba407bb69d8c9980a834cccd09f3b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 16:40:18 -0600 Subject: [PATCH 156/212] Add Model.deplete method to make user's life easier --- openmc/deplete/operator.py | 5 +++++ openmc/model/model.py | 39 +++++++++++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/openmc/deplete/operator.py b/openmc/deplete/operator.py index 1c62bdd401..a1d8ffb0b0 100644 --- a/openmc/deplete/operator.py +++ b/openmc/deplete/operator.py @@ -195,6 +195,11 @@ class Operator(TransportOperator): "material with ID={}.".format(mat.id)) volume[str(mat.id)] = mat.volume + # Make sure there are burnable materials + if not burnable_mats: + raise RuntimeError( + "No depletable materials were found in the model.") + # Sort the sets burnable_mats = sorted(burnable_mats, key=int) model_nuclides = sorted(model_nuclides) diff --git a/openmc/model/model.py b/openmc/model/model.py index 89fa84e604..d6e6ddce38 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -2,6 +2,10 @@ from collections.abc import Iterable import openmc from openmc.checkvalue import check_type +import openmc.deplete as dep + +_DEPLETE_METHODS = {'predictor': dep.integrator.predictor, + 'cecm': dep.integrator.cecm} class Model(object): @@ -136,9 +140,38 @@ class Model(object): for plot in plots: self._plots.append(plot) - def export_to_xml(self): - """Export model to XML files. + def deplete(self, timesteps, power, chain_file=None, method='cecm', **kwargs): + """Deplete model using specified timesteps/power + + Parameters + ---------- + timesteps : iterable of float + Array of timesteps in units of [s]. Note that values are not + cumulative. + power : float or iterable of float + Power of the reactor in [W]. A single value indicates that the power + is constant over all timesteps. An iterable indicates potentially + different power levels for each timestep. For a 2D problem, the + power can be given in [W/cm] as long as the "volume" assigned to a + depletion material is actually an area in [cm^2]. + chain_file : str, optional + Path to the depletion chain XML file. Defaults to the + :envvar:`OPENMC_DEPLETE_CHAIN` environment variable if it exists. + method : {'cecm', 'predictor'} + Integration method used for depletion + **kwargs + Keyword arguments passed to integration function (e.g., + :func:`openmc.deplete.integrator.cecm`) + """ + # Create OpenMC transport operator + op = dep.Operator(self.geometry, self.settings, chain_file) + + # Perform depletion + _DEPLETE_METHODS[method](op, timesteps, power, **kwargs) + + def export_to_xml(self): + """Export model to XML files.""" self.settings.export_to_xml() self.geometry.export_to_xml() @@ -166,7 +199,7 @@ class Model(object): Parameters ---------- **kwargs - All keyword arguments are passed to openmc.run + All keyword arguments are passed to :func:`openmc.run` Returns ------- From b4719cf53fbabc9f1aa60dba9608f4f101f71674 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Feb 2018 22:46:26 -0600 Subject: [PATCH 157/212] Fix for Python 3.4 (setting __doc__ on properties) --- openmc/deplete/abc.py | 8 ++++++-- openmc/deplete/nuclide.py | 21 ++++++++++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/openmc/deplete/abc.py b/openmc/deplete/abc.py index 8b42ee800e..8502909a21 100644 --- a/openmc/deplete/abc.py +++ b/openmc/deplete/abc.py @@ -23,8 +23,12 @@ rates : openmc.deplete.ReactionRates Resulting reaction rates """ -OperatorResult.k.__doc__ = None -OperatorResult.rates.__doc__ = None +try: + OperatorResult.k.__doc__ = None + OperatorResult.rates.__doc__ = None +except AttributeError: + # Can't set __doc__ on properties on Python 3.4 + pass class TransportOperator(metaclass=ABCMeta): diff --git a/openmc/deplete/nuclide.py b/openmc/deplete/nuclide.py index af10e5c2f9..8a30214c2c 100644 --- a/openmc/deplete/nuclide.py +++ b/openmc/deplete/nuclide.py @@ -24,9 +24,13 @@ branching_ratio : float Branching ratio of the decay mode """ -DecayTuple.type.__doc__ = None -DecayTuple.target.__doc__ = None -DecayTuple.branching_ratio.__doc__ = None +try: + DecayTuple.type.__doc__ = None + DecayTuple.target.__doc__ = None + DecayTuple.branching_ratio.__doc__ = None +except AttributeError: + # Can't set __doc__ on properties on Python 3.4 + pass ReactionTuple = namedtuple('ReactionTuple', 'type target Q branching_ratio') @@ -45,10 +49,13 @@ branching_ratio : float Branching ratio of the reaction """ -ReactionTuple.type.__doc__ = None -ReactionTuple.target.__doc__ = None -ReactionTuple.Q.__doc__ = None -ReactionTuple.branching_ratio.__doc__ = None +try: + ReactionTuple.type.__doc__ = None + ReactionTuple.target.__doc__ = None + ReactionTuple.Q.__doc__ = None + ReactionTuple.branching_ratio.__doc__ = None +except AttributeError: + pass class Nuclide(object): From 82d6c34d27e0021280581398be350e3f0df1a234 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 06:51:51 -0600 Subject: [PATCH 158/212] Move make_chain.py to openmc-make-depletion-chain --- .gitignore | 7 +--- openmc/_utils.py | 49 +++++++++++++++++++++++ scripts/example_run.py | 16 ++++---- scripts/make_chain.py | 60 ----------------------------- scripts/openmc-make-depletion-chain | 33 ++++++++++++++++ 5 files changed, 91 insertions(+), 74 deletions(-) create mode 100644 openmc/_utils.py delete mode 100644 scripts/make_chain.py create mode 100755 scripts/openmc-make-depletion-chain diff --git a/.gitignore b/.gitignore index 8c7cc3e366..65c7285af1 100644 --- a/.gitignore +++ b/.gitignore @@ -42,11 +42,8 @@ results_error.dat inputs_error.dat results_test.dat -# Test build files -tests/build/ -tests/coverage/ -tests/memcheck/ -tests/ctestscript.run +# Test +.pytest_cache/ # HDF5 files *.h5 diff --git a/openmc/_utils.py b/openmc/_utils.py new file mode 100644 index 0000000000..83455c17aa --- /dev/null +++ b/openmc/_utils.py @@ -0,0 +1,49 @@ +import os.path +from pathlib import Path +from urllib.parse import urlparse +from urllib.request import urlopen + +_BLOCK_SIZE = 16384 + + +def download(url): + """Download file from a URL + + Parameters + ---------- + url : str + URL from which to download + + Returns + ------- + basename : str + Name of file written locally + + """ + req = urlopen(url) + + # Get file size from header + file_size = req.length + + # Check if file already downloaded + basename = Path(urlparse(url).path).name + if os.path.exists(basename): + if os.path.getsize(basename) == file_size: + print('Skipping {}, already downloaded'.format(basename)) + return basename + + # Copy file to disk in chunks + print('Downloading {}... '.format(basename), end='') + downloaded = 0 + with open(basename, 'wb') as fh: + while True: + chunk = req.read(_BLOCK_SIZE) + if not chunk: + break + fh.write(chunk) + downloaded += len(chunk) + status = '{:10} [{:3.2f}%]'.format( + downloaded, downloaded * 100. / file_size) + print(status + '\b'*len(status), end='') + print('') + return basename diff --git a/scripts/example_run.py b/scripts/example_run.py index 30b6bdc2ee..36b6cce1a4 100644 --- a/scripts/example_run.py +++ b/scripts/example_run.py @@ -14,22 +14,20 @@ geometry, lower_left, upper_right = example_geometry.generate_problem() dt1 = 15*24*60*60 # 15 days dt2 = 5.5*30*24*60*60 # 5.5 months N = np.floor(dt2/dt1) - dt = np.repeat([dt1], N) -# Depletion settings -settings = openmc.deplete.OpenMCSettings() -settings.power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO -settings.dt_vec = dt -settings.output_dir = 'test' +# Power for simulation +power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO -# OpenMC-delegated settings +# OpenMC settings +settings = openmc.Settings() settings.particles = 1000 settings.batches = 100 settings.inactive = 40 settings.source = openmc.Source(space=openmc.stats.Box(lower_left, upper_right)) -op = openmc.deplete.OpenMCOperator(geometry, settings) +op = openmc.deplete.Operator(geometry, settings) +op.output_dir = 'test' # Perform simulation using the MCNPX/MCNP6 algorithm -openmc.deplete.integrator.cecm(op) +openmc.deplete.integrator.cecm(op, dt, power) diff --git a/scripts/make_chain.py b/scripts/make_chain.py deleted file mode 100644 index 6d64f34b3c..0000000000 --- a/scripts/make_chain.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python - -import glob -import os -from zipfile import ZipFile - -import requests -from tqdm import tqdm -import openmc.deplete - - -urls = [ - 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-neutrons.zip', - 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-decay.zip', - 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-nfy.zip' -] - - -def download_file(url): - response = requests.get(url, stream=True) - filesize = int(response.headers.get('content-length')) - - # Check if file already downloaded - basename = url.split('/')[-1] - if os.path.exists(basename): - if os.path.getsize(basename) == filesize: - return basename - else: - overwrite = input('Overwrite {}? ([y]/n) '.format(basename)) - if overwrite.lower().startswith('n'): - return basename - - with open(basename, 'wb') as f: - with tqdm(desc='Downloading {}'.format(basename), - total=filesize, unit='B', unit_scale=True) as pbar: - for i, chunk in enumerate(response.iter_content(chunk_size=4096)): - pbar.update(4096) - if chunk: - f.write(chunk) - - return basename - - -def main(): - for url in urls: - basename = download_file(url) - with ZipFile(basename, 'r') as zf: - print('Extracting {}...'.format(basename)) - zf.extractall() - - decay_files = glob.glob(os.path.join('decay', '*.endf')) - nfy_files = glob.glob(os.path.join('nfy', '*.endf')) - neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) - - chain = openmc.deplete.Chain.from_endf(decay_files, nfy_files, neutron_files) - chain.export_to_xml('chain_endfb71.xml') - - -if __name__ == '__main__': - main() diff --git a/scripts/openmc-make-depletion-chain b/scripts/openmc-make-depletion-chain new file mode 100755 index 0000000000..7c08f984e9 --- /dev/null +++ b/scripts/openmc-make-depletion-chain @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 + +import glob +import os +from zipfile import ZipFile + +from openmc._utils import download +import openmc.deplete + + +URLS = [ + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-neutrons.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-decay.zip', + 'http://www.nndc.bnl.gov/endf/b7.1/zips/ENDF-B-VII.1-nfy.zip' +] + +def main(): + for url in URLS: + basename = download(url) + with ZipFile(basename, 'r') as zf: + print('Extracting {}...'.format(basename)) + zf.extractall() + + decay_files = glob.glob(os.path.join('decay', '*.endf')) + nfy_files = glob.glob(os.path.join('nfy', '*.endf')) + neutron_files = glob.glob(os.path.join('neutrons', '*.endf')) + + chain = openmc.deplete.Chain.from_endf(decay_files, nfy_files, neutron_files) + chain.export_to_xml('chain_endfb71.xml') + + +if __name__ == '__main__': + main() From d981b34dc18236cf857d1249629b6437005e073f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 07:00:20 -0600 Subject: [PATCH 159/212] Remove FutureWarning for capi import --- openmc/capi/__init__.py | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/openmc/capi/__init__.py b/openmc/capi/__init__.py index d302001c99..bc173f9946 100644 --- a/openmc/capi/__init__.py +++ b/openmc/capi/__init__.py @@ -15,7 +15,6 @@ objects in the :mod:`openmc.capi` subpackage, for example: from ctypes import CDLL import os import sys -from warnings import warn import pkg_resources @@ -36,10 +35,7 @@ else: # available. Instead, we create a mock object so that when the modules # within the openmc.capi package try to configure arguments and return # values for symbols, no errors occur - try: - from unittest.mock import Mock - except ImportError: - from mock import Mock + from unittest.mock import Mock _dll = Mock() from .error import * @@ -50,6 +46,3 @@ from .cell import * from .filter import * from .tally import * from .settings import settings - -warn("The Python bindings to OpenMC's C API are still unstable " - "and may change substantially in future releases.", FutureWarning) From 81b859ad4ff3995ac84e27b8bf15ba2f87cc4cc4 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 07:33:18 -0600 Subject: [PATCH 160/212] Get rid of example_run.py and example_plot.py --- scripts/example_geometry.py | 378 -------------------- scripts/example_plot.py | 43 --- scripts/example_run.py | 33 -- tests/regression_tests/example_geometry.py | 379 ++++++++++++++++++++- 4 files changed, 378 insertions(+), 455 deletions(-) delete mode 100644 scripts/example_geometry.py delete mode 100644 scripts/example_plot.py delete mode 100644 scripts/example_run.py mode change 120000 => 100644 tests/regression_tests/example_geometry.py diff --git a/scripts/example_geometry.py b/scripts/example_geometry.py deleted file mode 100644 index ca10c1f725..0000000000 --- a/scripts/example_geometry.py +++ /dev/null @@ -1,378 +0,0 @@ -"""An example file showing how to make a geometry. - -This particular example creates a 3x3 geometry, with 8 regular pins and one -Gd-157 2 wt-percent enriched. All pins are segmented. -""" - -from collections import OrderedDict -import math - -import numpy as np -import openmc - - -def density_to_mat(dens_dict): - """Generates an OpenMC material from a cell ID and self.number_density. - - Parameters - ---------- - dens_dict : dict - Dictionary mapping nuclide names to densities - - Returns - ------- - openmc.Material - The OpenMC material filled with nuclides. - - """ - mat = openmc.Material() - for key in dens_dict: - mat.add_nuclide(key, 1.0e-24*dens_dict[key]) - mat.set_density('sum') - - return mat - - -def generate_initial_number_density(): - """ Generates initial number density. - - These results were from a CASMO5 run in which the gadolinium pin was - loaded with 2 wt percent of Gd-157. - """ - - # Concentration to be used for all fuel pins - fuel_dict = OrderedDict() - fuel_dict['U235'] = 1.05692e21 - fuel_dict['U234'] = 1.00506e19 - fuel_dict['U238'] = 2.21371e22 - fuel_dict['O16'] = 4.62954e22 - fuel_dict['O17'] = 1.127684e20 - fuel_dict['I135'] = 1.0e10 - fuel_dict['Xe135'] = 1.0e10 - fuel_dict['Xe136'] = 1.0e10 - fuel_dict['Cs135'] = 1.0e10 - fuel_dict['Gd156'] = 1.0e10 - fuel_dict['Gd157'] = 1.0e10 - # fuel_dict['O18'] = 9.51352e19 # Does not exist in ENDF71, merged into 17 - - # Concentration to be used for the gadolinium fuel pin - fuel_gd_dict = OrderedDict() - fuel_gd_dict['U235'] = 1.03579e21 - fuel_gd_dict['U238'] = 2.16943e22 - fuel_gd_dict['Gd156'] = 3.95517E+10 - fuel_gd_dict['Gd157'] = 1.08156e20 - fuel_gd_dict['O16'] = 4.64035e22 - fuel_dict['I135'] = 1.0e10 - fuel_dict['Xe136'] = 1.0e10 - fuel_dict['Xe135'] = 1.0e10 - fuel_dict['Cs135'] = 1.0e10 - # There are a whole bunch of 1e-10 stuff here. - - # Concentration to be used for cladding - clad_dict = OrderedDict() - clad_dict['O16'] = 3.07427e20 - clad_dict['O17'] = 7.48868e17 - clad_dict['Cr50'] = 3.29620e18 - clad_dict['Cr52'] = 6.35639e19 - clad_dict['Cr53'] = 7.20763e18 - clad_dict['Cr54'] = 1.79413e18 - clad_dict['Fe54'] = 5.57350e18 - clad_dict['Fe56'] = 8.74921e19 - clad_dict['Fe57'] = 2.02057e18 - clad_dict['Fe58'] = 2.68901e17 - clad_dict['Cr50'] = 3.29620e18 - clad_dict['Cr52'] = 6.35639e19 - clad_dict['Cr53'] = 7.20763e18 - clad_dict['Cr54'] = 1.79413e18 - clad_dict['Ni58'] = 2.51631e19 - clad_dict['Ni60'] = 9.69278e18 - clad_dict['Ni61'] = 4.21338e17 - clad_dict['Ni62'] = 1.34341e18 - clad_dict['Ni64'] = 3.43127e17 - clad_dict['Zr90'] = 2.18320e22 - clad_dict['Zr91'] = 4.76104e21 - clad_dict['Zr92'] = 7.27734e21 - clad_dict['Zr94'] = 7.37494e21 - clad_dict['Zr96'] = 1.18814e21 - clad_dict['Sn112'] = 4.67352e18 - clad_dict['Sn114'] = 3.17992e18 - clad_dict['Sn115'] = 1.63814e18 - clad_dict['Sn116'] = 7.00546e19 - clad_dict['Sn117'] = 3.70027e19 - clad_dict['Sn118'] = 1.16694e20 - clad_dict['Sn119'] = 4.13872e19 - clad_dict['Sn120'] = 1.56973e20 - clad_dict['Sn122'] = 2.23076e19 - clad_dict['Sn124'] = 2.78966e19 - - # Gap concentration - # Funny enough, the example problem uses air. - gap_dict = OrderedDict() - gap_dict['O16'] = 7.86548e18 - gap_dict['O17'] = 2.99548e15 - gap_dict['N14'] = 3.38646e19 - gap_dict['N15'] = 1.23717e17 - - # Concentration to be used for coolant - # No boron - cool_dict = OrderedDict() - cool_dict['H1'] = 4.68063e22 - cool_dict['O16'] = 2.33427e22 - cool_dict['O17'] = 8.89086e18 - - # Store these dictionaries in the initial conditions dictionary - initial_density = OrderedDict() - initial_density['fuel_gd'] = fuel_gd_dict - initial_density['fuel'] = fuel_dict - initial_density['gap'] = gap_dict - initial_density['clad'] = clad_dict - initial_density['cool'] = cool_dict - - # Set up libraries to use - temperature = OrderedDict() - sab = OrderedDict() - - # Toggle betweeen MCNP and NNDC data - MCNP = False - - if MCNP: - temperature['fuel_gd'] = 900.0 - temperature['fuel'] = 900.0 - # We approximate temperature of everything as 600K, even though it was - # actually 580K. - temperature['gap'] = 600.0 - temperature['clad'] = 600.0 - temperature['cool'] = 600.0 - else: - temperature['fuel_gd'] = 293.6 - temperature['fuel'] = 293.6 - temperature['gap'] = 293.6 - temperature['clad'] = 293.6 - temperature['cool'] = 293.6 - - sab['cool'] = 'c_H_in_H2O' - - # Set up burnable materials - burn = OrderedDict() - burn['fuel_gd'] = True - burn['fuel'] = True - burn['gap'] = False - burn['clad'] = False - burn['cool'] = False - - return temperature, sab, initial_density, burn - -def segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad): - """ Calculates a segmented pin. - - Separates a pin with n_rings and n_wedges. All cells have equal volume. - Pin is centered at origin. - """ - - # Calculate all the volumes of interest - v_fuel = math.pi * r_fuel**2 - v_gap = math.pi * r_gap**2 - v_fuel - v_clad = math.pi * r_clad**2 - v_fuel - v_gap - v_ring = v_fuel / n_rings - v_segment = v_ring / n_wedges - - # Compute ring radiuses - r_rings = np.zeros(n_rings) - - for i in range(n_rings): - r_rings[i] = math.sqrt(1.0/(math.pi) * v_ring * (i+1)) - - # Compute thetas - theta = np.linspace(0, 2*math.pi, n_wedges + 1) - - # Compute surfaces - fuel_rings = [openmc.ZCylinder(x0=0, y0=0, R=r_rings[i]) - for i in range(n_rings)] - - fuel_wedges = [openmc.Plane(A=math.cos(theta[i]), B=math.sin(theta[i])) - for i in range(n_wedges)] - - gap_ring = openmc.ZCylinder(x0=0, y0=0, R=r_gap) - clad_ring = openmc.ZCylinder(x0=0, y0=0, R=r_clad) - - # Create cells - fuel_cells = [] - if n_wedges == 1: - for i in range(n_rings): - cell = openmc.Cell(name='fuel') - if i == 0: - cell.region = -fuel_rings[0] - else: - cell.region = +fuel_rings[i-1] & -fuel_rings[i] - fuel_cells.append(cell) - else: - for i in range(n_rings): - for j in range(n_wedges): - cell = openmc.Cell(name='fuel') - if i == 0: - if j != n_wedges-1: - cell.region = (-fuel_rings[0] - & +fuel_wedges[j] - & -fuel_wedges[j+1]) - else: - cell.region = (-fuel_rings[0] - & +fuel_wedges[j] - & -fuel_wedges[0]) - else: - if j != n_wedges-1: - cell.region = (+fuel_rings[i-1] - & -fuel_rings[i] - & +fuel_wedges[j] - & -fuel_wedges[j+1]) - else: - cell.region = (+fuel_rings[i-1] - & -fuel_rings[i] - & +fuel_wedges[j] - & -fuel_wedges[0]) - fuel_cells.append(cell) - - # Gap ring - gap_cell = openmc.Cell(name='gap') - gap_cell.region = +fuel_rings[-1] & -gap_ring - fuel_cells.append(gap_cell) - - # Clad ring - clad_cell = openmc.Cell(name='clad') - clad_cell.region = +gap_ring & -clad_ring - fuel_cells.append(clad_cell) - - # Moderator - mod_cell = openmc.Cell(name='cool') - mod_cell.region = +clad_ring - fuel_cells.append(mod_cell) - - # Form universe - fuel_u = openmc.Universe() - fuel_u.add_cells(fuel_cells) - - return fuel_u, v_segment, v_gap, v_clad - -def generate_geometry(n_rings, n_wedges): - """ Generates example geometry. - - This function creates the initial geometry, a 9 pin reflective problem. - One pin, containing gadolinium, is discretized into sectors. - - In addition to what one would do with the general OpenMC geometry code, it - is necessary to create a dictionary, volume, that maps a cell ID to a - volume. Further, by naming cells the same as the above materials, the code - can automatically handle the mapping. - - Parameters - ---------- - n_rings : int - Number of rings to generate for the geometry - n_wedges : int - Number of wedges to generate for the geometry - """ - - pitch = 1.26197 - r_fuel = 0.412275 - r_gap = 0.418987 - r_clad = 0.476121 - - n_pin = 3 - - # This table describes the 'fuel' to actual type mapping - # It's not necessary to do it this way. Just adjust the initial conditions - # below. - mapping = ['fuel', 'fuel', 'fuel', - 'fuel', 'fuel_gd', 'fuel', - 'fuel', 'fuel', 'fuel'] - - # Form pin cell - fuel_u, v_segment, v_gap, v_clad = segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad) - - # Form lattice - all_water_c = openmc.Cell(name='cool') - all_water_u = openmc.Universe(cells=(all_water_c, )) - - lattice = openmc.RectLattice() - lattice.pitch = [pitch]*2 - lattice.lower_left = [-pitch*n_pin/2, -pitch*n_pin/2] - lattice_array = [[fuel_u for i in range(n_pin)] for j in range(n_pin)] - lattice.universes = lattice_array - lattice.outer = all_water_u - - # Bound universe - x_low = openmc.XPlane(x0=-pitch*n_pin/2, boundary_type='reflective') - x_high = openmc.XPlane(x0=pitch*n_pin/2, boundary_type='reflective') - y_low = openmc.YPlane(y0=-pitch*n_pin/2, boundary_type='reflective') - y_high = openmc.YPlane(y0=pitch*n_pin/2, boundary_type='reflective') - z_low = openmc.ZPlane(z0=-10, boundary_type='reflective') - z_high = openmc.ZPlane(z0=10, boundary_type='reflective') - - # Compute bounding box - lower_left = [-pitch*n_pin/2, -pitch*n_pin/2, -10] - upper_right = [pitch*n_pin/2, pitch*n_pin/2, 10] - - root_c = openmc.Cell(fill=lattice) - root_c.region = (+x_low & -x_high - & +y_low & -y_high - & +z_low & -z_high) - root_u = openmc.Universe(universe_id=0, cells=(root_c, )) - geometry = openmc.Geometry(root_u) - - v_cool = pitch**2 - (v_gap + v_clad + n_rings * n_wedges * v_segment) - - # Store volumes for later usage - volume = {'fuel': v_segment, 'gap':v_gap, 'clad':v_clad, 'cool':v_cool} - - return geometry, volume, mapping, lower_left, upper_right - -def generate_problem(n_rings=5, n_wedges=8): - """ Merges geometry and materials. - - This function initializes the materials for each cell using the dictionaries - provided by generate_initial_number_density. It is assumed a cell named - 'fuel' will have further region differentiation (see mapping). - - Parameters - ---------- - n_rings : int, optional - Number of rings to generate for the geometry - n_wedges : int, optional - Number of wedges to generate for the geometry - """ - - # Get materials dictionary, geometry, and volumes - temperature, sab, initial_density, burn = generate_initial_number_density() - geometry, volume, mapping, lower_left, upper_right = generate_geometry(n_rings, n_wedges) - - # Apply distribmats, fill geometry - cells = geometry.root_universe.get_all_cells() - for cell_id in cells: - cell = cells[cell_id] - if cell.name == 'fuel': - - omc_mats = [] - - for cell_type in mapping: - omc_mat = density_to_mat(initial_density[cell_type]) - - if cell_type in sab: - omc_mat.add_s_alpha_beta(sab[cell_type]) - omc_mat.temperature = temperature[cell_type] - omc_mat.depletable = burn[cell_type] - omc_mat.volume = volume['fuel'] - - omc_mats.append(omc_mat) - - cell.fill = omc_mats - elif cell.name != '': - omc_mat = density_to_mat(initial_density[cell.name]) - - if cell.name in sab: - omc_mat.add_s_alpha_beta(sab[cell.name]) - omc_mat.temperature = temperature[cell.name] - omc_mat.depletable = burn[cell.name] - omc_mat.volume = volume[cell.name] - - cell.fill = omc_mat - - return geometry, lower_left, upper_right diff --git a/scripts/example_plot.py b/scripts/example_plot.py deleted file mode 100644 index ab5ac204d8..0000000000 --- a/scripts/example_plot.py +++ /dev/null @@ -1,43 +0,0 @@ -"""An example file showing how to plot data from a simulation.""" - -import matplotlib.pyplot as plt -from openmc.deplete import (read_results, evaluate_single_nuclide, - evaluate_reaction_rate, evaluate_eigenvalue) - -# Set variables for where the data is, and what we want to read out. -result_folder = "test" - -# Load data -results = read_results(result_folder + "/deplete_results.h5") - -cell = "5" -nuc = "Gd157" -rxn = "(n,gamma)" - -# Total number of nuclides -plt.figure() -# Pointwise data -x, y = evaluate_single_nuclide(results, cell, nuc) -plt.semilogy(x, y) - -plt.xlabel("Time, s") -plt.ylabel("Total Number") -plt.savefig("number.pdf") - -# Reaction rate -plt.figure() -x, y = evaluate_reaction_rate(results, cell, nuc, rxn) -plt.plot(x, y) -plt.xlabel("Time, s") -plt.ylabel("Reaction Rate, 1/s") - -plt.savefig("rate.pdf") - -# Eigenvalue -plt.figure() -x, y = evaluate_eigenvalue(results) -plt.plot(x, y) -plt.xlabel("Time, s") -plt.ylabel("Eigenvalue") - -plt.savefig("eigvl.pdf") diff --git a/scripts/example_run.py b/scripts/example_run.py deleted file mode 100644 index 36b6cce1a4..0000000000 --- a/scripts/example_run.py +++ /dev/null @@ -1,33 +0,0 @@ -"""An example file showing how to run a simulation.""" - -import numpy as np -import openmc -from openmc.data import JOULE_PER_EV -import openmc.deplete - -import example_geometry - -# Load geometry from example -geometry, lower_left, upper_right = example_geometry.generate_problem() - -# Create dt vector for 5.5 months with 15 day timesteps -dt1 = 15*24*60*60 # 15 days -dt2 = 5.5*30*24*60*60 # 5.5 months -N = np.floor(dt2/dt1) -dt = np.repeat([dt1], N) - -# Power for simulation -power = 2.337e15*4*JOULE_PER_EV*1e6 # MeV/second cm from CASMO - -# OpenMC settings -settings = openmc.Settings() -settings.particles = 1000 -settings.batches = 100 -settings.inactive = 40 -settings.source = openmc.Source(space=openmc.stats.Box(lower_left, upper_right)) - -op = openmc.deplete.Operator(geometry, settings) -op.output_dir = 'test' - -# Perform simulation using the MCNPX/MCNP6 algorithm -openmc.deplete.integrator.cecm(op, dt, power) diff --git a/tests/regression_tests/example_geometry.py b/tests/regression_tests/example_geometry.py deleted file mode 120000 index 1071aabc05..0000000000 --- a/tests/regression_tests/example_geometry.py +++ /dev/null @@ -1 +0,0 @@ -../../scripts/example_geometry.py \ No newline at end of file diff --git a/tests/regression_tests/example_geometry.py b/tests/regression_tests/example_geometry.py new file mode 100644 index 0000000000..ca10c1f725 --- /dev/null +++ b/tests/regression_tests/example_geometry.py @@ -0,0 +1,378 @@ +"""An example file showing how to make a geometry. + +This particular example creates a 3x3 geometry, with 8 regular pins and one +Gd-157 2 wt-percent enriched. All pins are segmented. +""" + +from collections import OrderedDict +import math + +import numpy as np +import openmc + + +def density_to_mat(dens_dict): + """Generates an OpenMC material from a cell ID and self.number_density. + + Parameters + ---------- + dens_dict : dict + Dictionary mapping nuclide names to densities + + Returns + ------- + openmc.Material + The OpenMC material filled with nuclides. + + """ + mat = openmc.Material() + for key in dens_dict: + mat.add_nuclide(key, 1.0e-24*dens_dict[key]) + mat.set_density('sum') + + return mat + + +def generate_initial_number_density(): + """ Generates initial number density. + + These results were from a CASMO5 run in which the gadolinium pin was + loaded with 2 wt percent of Gd-157. + """ + + # Concentration to be used for all fuel pins + fuel_dict = OrderedDict() + fuel_dict['U235'] = 1.05692e21 + fuel_dict['U234'] = 1.00506e19 + fuel_dict['U238'] = 2.21371e22 + fuel_dict['O16'] = 4.62954e22 + fuel_dict['O17'] = 1.127684e20 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + fuel_dict['Gd156'] = 1.0e10 + fuel_dict['Gd157'] = 1.0e10 + # fuel_dict['O18'] = 9.51352e19 # Does not exist in ENDF71, merged into 17 + + # Concentration to be used for the gadolinium fuel pin + fuel_gd_dict = OrderedDict() + fuel_gd_dict['U235'] = 1.03579e21 + fuel_gd_dict['U238'] = 2.16943e22 + fuel_gd_dict['Gd156'] = 3.95517E+10 + fuel_gd_dict['Gd157'] = 1.08156e20 + fuel_gd_dict['O16'] = 4.64035e22 + fuel_dict['I135'] = 1.0e10 + fuel_dict['Xe136'] = 1.0e10 + fuel_dict['Xe135'] = 1.0e10 + fuel_dict['Cs135'] = 1.0e10 + # There are a whole bunch of 1e-10 stuff here. + + # Concentration to be used for cladding + clad_dict = OrderedDict() + clad_dict['O16'] = 3.07427e20 + clad_dict['O17'] = 7.48868e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Fe54'] = 5.57350e18 + clad_dict['Fe56'] = 8.74921e19 + clad_dict['Fe57'] = 2.02057e18 + clad_dict['Fe58'] = 2.68901e17 + clad_dict['Cr50'] = 3.29620e18 + clad_dict['Cr52'] = 6.35639e19 + clad_dict['Cr53'] = 7.20763e18 + clad_dict['Cr54'] = 1.79413e18 + clad_dict['Ni58'] = 2.51631e19 + clad_dict['Ni60'] = 9.69278e18 + clad_dict['Ni61'] = 4.21338e17 + clad_dict['Ni62'] = 1.34341e18 + clad_dict['Ni64'] = 3.43127e17 + clad_dict['Zr90'] = 2.18320e22 + clad_dict['Zr91'] = 4.76104e21 + clad_dict['Zr92'] = 7.27734e21 + clad_dict['Zr94'] = 7.37494e21 + clad_dict['Zr96'] = 1.18814e21 + clad_dict['Sn112'] = 4.67352e18 + clad_dict['Sn114'] = 3.17992e18 + clad_dict['Sn115'] = 1.63814e18 + clad_dict['Sn116'] = 7.00546e19 + clad_dict['Sn117'] = 3.70027e19 + clad_dict['Sn118'] = 1.16694e20 + clad_dict['Sn119'] = 4.13872e19 + clad_dict['Sn120'] = 1.56973e20 + clad_dict['Sn122'] = 2.23076e19 + clad_dict['Sn124'] = 2.78966e19 + + # Gap concentration + # Funny enough, the example problem uses air. + gap_dict = OrderedDict() + gap_dict['O16'] = 7.86548e18 + gap_dict['O17'] = 2.99548e15 + gap_dict['N14'] = 3.38646e19 + gap_dict['N15'] = 1.23717e17 + + # Concentration to be used for coolant + # No boron + cool_dict = OrderedDict() + cool_dict['H1'] = 4.68063e22 + cool_dict['O16'] = 2.33427e22 + cool_dict['O17'] = 8.89086e18 + + # Store these dictionaries in the initial conditions dictionary + initial_density = OrderedDict() + initial_density['fuel_gd'] = fuel_gd_dict + initial_density['fuel'] = fuel_dict + initial_density['gap'] = gap_dict + initial_density['clad'] = clad_dict + initial_density['cool'] = cool_dict + + # Set up libraries to use + temperature = OrderedDict() + sab = OrderedDict() + + # Toggle betweeen MCNP and NNDC data + MCNP = False + + if MCNP: + temperature['fuel_gd'] = 900.0 + temperature['fuel'] = 900.0 + # We approximate temperature of everything as 600K, even though it was + # actually 580K. + temperature['gap'] = 600.0 + temperature['clad'] = 600.0 + temperature['cool'] = 600.0 + else: + temperature['fuel_gd'] = 293.6 + temperature['fuel'] = 293.6 + temperature['gap'] = 293.6 + temperature['clad'] = 293.6 + temperature['cool'] = 293.6 + + sab['cool'] = 'c_H_in_H2O' + + # Set up burnable materials + burn = OrderedDict() + burn['fuel_gd'] = True + burn['fuel'] = True + burn['gap'] = False + burn['clad'] = False + burn['cool'] = False + + return temperature, sab, initial_density, burn + +def segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad): + """ Calculates a segmented pin. + + Separates a pin with n_rings and n_wedges. All cells have equal volume. + Pin is centered at origin. + """ + + # Calculate all the volumes of interest + v_fuel = math.pi * r_fuel**2 + v_gap = math.pi * r_gap**2 - v_fuel + v_clad = math.pi * r_clad**2 - v_fuel - v_gap + v_ring = v_fuel / n_rings + v_segment = v_ring / n_wedges + + # Compute ring radiuses + r_rings = np.zeros(n_rings) + + for i in range(n_rings): + r_rings[i] = math.sqrt(1.0/(math.pi) * v_ring * (i+1)) + + # Compute thetas + theta = np.linspace(0, 2*math.pi, n_wedges + 1) + + # Compute surfaces + fuel_rings = [openmc.ZCylinder(x0=0, y0=0, R=r_rings[i]) + for i in range(n_rings)] + + fuel_wedges = [openmc.Plane(A=math.cos(theta[i]), B=math.sin(theta[i])) + for i in range(n_wedges)] + + gap_ring = openmc.ZCylinder(x0=0, y0=0, R=r_gap) + clad_ring = openmc.ZCylinder(x0=0, y0=0, R=r_clad) + + # Create cells + fuel_cells = [] + if n_wedges == 1: + for i in range(n_rings): + cell = openmc.Cell(name='fuel') + if i == 0: + cell.region = -fuel_rings[0] + else: + cell.region = +fuel_rings[i-1] & -fuel_rings[i] + fuel_cells.append(cell) + else: + for i in range(n_rings): + for j in range(n_wedges): + cell = openmc.Cell(name='fuel') + if i == 0: + if j != n_wedges-1: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (-fuel_rings[0] + & +fuel_wedges[j] + & -fuel_wedges[0]) + else: + if j != n_wedges-1: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[j+1]) + else: + cell.region = (+fuel_rings[i-1] + & -fuel_rings[i] + & +fuel_wedges[j] + & -fuel_wedges[0]) + fuel_cells.append(cell) + + # Gap ring + gap_cell = openmc.Cell(name='gap') + gap_cell.region = +fuel_rings[-1] & -gap_ring + fuel_cells.append(gap_cell) + + # Clad ring + clad_cell = openmc.Cell(name='clad') + clad_cell.region = +gap_ring & -clad_ring + fuel_cells.append(clad_cell) + + # Moderator + mod_cell = openmc.Cell(name='cool') + mod_cell.region = +clad_ring + fuel_cells.append(mod_cell) + + # Form universe + fuel_u = openmc.Universe() + fuel_u.add_cells(fuel_cells) + + return fuel_u, v_segment, v_gap, v_clad + +def generate_geometry(n_rings, n_wedges): + """ Generates example geometry. + + This function creates the initial geometry, a 9 pin reflective problem. + One pin, containing gadolinium, is discretized into sectors. + + In addition to what one would do with the general OpenMC geometry code, it + is necessary to create a dictionary, volume, that maps a cell ID to a + volume. Further, by naming cells the same as the above materials, the code + can automatically handle the mapping. + + Parameters + ---------- + n_rings : int + Number of rings to generate for the geometry + n_wedges : int + Number of wedges to generate for the geometry + """ + + pitch = 1.26197 + r_fuel = 0.412275 + r_gap = 0.418987 + r_clad = 0.476121 + + n_pin = 3 + + # This table describes the 'fuel' to actual type mapping + # It's not necessary to do it this way. Just adjust the initial conditions + # below. + mapping = ['fuel', 'fuel', 'fuel', + 'fuel', 'fuel_gd', 'fuel', + 'fuel', 'fuel', 'fuel'] + + # Form pin cell + fuel_u, v_segment, v_gap, v_clad = segment_pin(n_rings, n_wedges, r_fuel, r_gap, r_clad) + + # Form lattice + all_water_c = openmc.Cell(name='cool') + all_water_u = openmc.Universe(cells=(all_water_c, )) + + lattice = openmc.RectLattice() + lattice.pitch = [pitch]*2 + lattice.lower_left = [-pitch*n_pin/2, -pitch*n_pin/2] + lattice_array = [[fuel_u for i in range(n_pin)] for j in range(n_pin)] + lattice.universes = lattice_array + lattice.outer = all_water_u + + # Bound universe + x_low = openmc.XPlane(x0=-pitch*n_pin/2, boundary_type='reflective') + x_high = openmc.XPlane(x0=pitch*n_pin/2, boundary_type='reflective') + y_low = openmc.YPlane(y0=-pitch*n_pin/2, boundary_type='reflective') + y_high = openmc.YPlane(y0=pitch*n_pin/2, boundary_type='reflective') + z_low = openmc.ZPlane(z0=-10, boundary_type='reflective') + z_high = openmc.ZPlane(z0=10, boundary_type='reflective') + + # Compute bounding box + lower_left = [-pitch*n_pin/2, -pitch*n_pin/2, -10] + upper_right = [pitch*n_pin/2, pitch*n_pin/2, 10] + + root_c = openmc.Cell(fill=lattice) + root_c.region = (+x_low & -x_high + & +y_low & -y_high + & +z_low & -z_high) + root_u = openmc.Universe(universe_id=0, cells=(root_c, )) + geometry = openmc.Geometry(root_u) + + v_cool = pitch**2 - (v_gap + v_clad + n_rings * n_wedges * v_segment) + + # Store volumes for later usage + volume = {'fuel': v_segment, 'gap':v_gap, 'clad':v_clad, 'cool':v_cool} + + return geometry, volume, mapping, lower_left, upper_right + +def generate_problem(n_rings=5, n_wedges=8): + """ Merges geometry and materials. + + This function initializes the materials for each cell using the dictionaries + provided by generate_initial_number_density. It is assumed a cell named + 'fuel' will have further region differentiation (see mapping). + + Parameters + ---------- + n_rings : int, optional + Number of rings to generate for the geometry + n_wedges : int, optional + Number of wedges to generate for the geometry + """ + + # Get materials dictionary, geometry, and volumes + temperature, sab, initial_density, burn = generate_initial_number_density() + geometry, volume, mapping, lower_left, upper_right = generate_geometry(n_rings, n_wedges) + + # Apply distribmats, fill geometry + cells = geometry.root_universe.get_all_cells() + for cell_id in cells: + cell = cells[cell_id] + if cell.name == 'fuel': + + omc_mats = [] + + for cell_type in mapping: + omc_mat = density_to_mat(initial_density[cell_type]) + + if cell_type in sab: + omc_mat.add_s_alpha_beta(sab[cell_type]) + omc_mat.temperature = temperature[cell_type] + omc_mat.depletable = burn[cell_type] + omc_mat.volume = volume['fuel'] + + omc_mats.append(omc_mat) + + cell.fill = omc_mats + elif cell.name != '': + omc_mat = density_to_mat(initial_density[cell.name]) + + if cell.name in sab: + omc_mat.add_s_alpha_beta(sab[cell.name]) + omc_mat.temperature = temperature[cell.name] + omc_mat.depletable = burn[cell.name] + omc_mat.volume = volume[cell.name] + + cell.fill = omc_mat + + return geometry, lower_left, upper_right From d7f1904e41cb8e00578c476c7ec75a62d9174101 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 10:15:42 -0600 Subject: [PATCH 161/212] Move simple chains into tests directory --- {chains => tests}/chain_simple.xml | 0 {chains => tests}/chain_test.xml | 0 tests/regression_tests/test_deplete_full.py | 2 +- tests/unit_tests/test_deplete_chain.py | 2 +- 4 files changed, 2 insertions(+), 2 deletions(-) rename {chains => tests}/chain_simple.xml (100%) rename {chains => tests}/chain_test.xml (100%) diff --git a/chains/chain_simple.xml b/tests/chain_simple.xml similarity index 100% rename from chains/chain_simple.xml rename to tests/chain_simple.xml diff --git a/chains/chain_test.xml b/tests/chain_test.xml similarity index 100% rename from chains/chain_test.xml rename to tests/chain_test.xml diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index 2286af908a..fb31ac0c03 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -43,7 +43,7 @@ def test_full(run_in_tmpdir): settings.verbosity = 3 # Create operator - chain_file = Path(__file__).parents[2] / 'chains' / 'chain_simple.xml' + chain_file = Path(__file__).parents[1] / 'chain_simple.xml' op = openmc.deplete.Operator(geometry, settings, chain_file) op.round_number = True diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 7ac3e2f8dd..8fc01b4270 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -8,7 +8,7 @@ import numpy as np from openmc.deplete import comm, Chain, reaction_rates, nuclide -_test_filename = str(Path(__file__).parents[2] / 'chains' / 'chain_test.xml') +_test_filename = str(Path(__file__).parents[1] / 'chain_test.xml') def test_init(): From 7ef5174274fb4fb034d0fb710db6e5b5a1756858 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 10:31:57 -0600 Subject: [PATCH 162/212] Move test chain directly into test_deplete_chain --- tests/chain_test.xml | 23 ------------ tests/unit_tests/test_deplete_chain.py | 48 ++++++++++++++++++++++---- 2 files changed, 41 insertions(+), 30 deletions(-) delete mode 100644 tests/chain_test.xml diff --git a/tests/chain_test.xml b/tests/chain_test.xml deleted file mode 100644 index c8c75ad7b3..0000000000 --- a/tests/chain_test.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - 0.0253 - - A B - 0.0292737 0.002566345 - - - - diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 8fc01b4270..f7e7899a30 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -6,9 +6,44 @@ from pathlib import Path import numpy as np from openmc.deplete import comm, Chain, reaction_rates, nuclide +import pytest + +from tests import cdtemp -_test_filename = str(Path(__file__).parents[1] / 'chain_test.xml') +_TEST_CHAIN = """\ + + + + + + + + + + + + + + + + 0.0253 + + A B + 0.0292737 0.002566345 + + + + +""" + + +@pytest.fixture(scope='module') +def simple_chain(): + with cdtemp(): + with open('chain_test.xml', 'w') as fh: + fh.write(_TEST_CHAIN) + yield Chain.from_xml('chain_test.xml') def test_init(): @@ -33,13 +68,13 @@ def test_from_endf(): pass -def test_from_xml(): +def test_from_xml(simple_chain): """Read chain_test.xml and ensure all values are correct.""" # Unfortunately, this routine touches a lot of the code, but most of # the components external to depletion_chain.py are simple storage # types. - chain = Chain.from_xml(_test_filename) + chain = simple_chain # Basic checks assert len(chain) == 3 @@ -125,16 +160,15 @@ def test_export_to_xml(run_in_tmpdir): chain.nuclides = [A, B, C] chain.export_to_xml(filename) - original = open(_test_filename, 'r').read() chain_xml = open(filename, 'r').read() - assert original == chain_xml + assert _TEST_CHAIN == chain_xml -def test_form_matrix(): +def test_form_matrix(simple_chain): """ Using chain_test, and a dummy reaction rate, compute the matrix. """ # Relies on test_from_xml passing. - chain = Chain.from_xml(_test_filename) + chain = simple_chain mats = ["10000", "10001"] nuclides = ["A", "B", "C"] From 8a4cdf39921ed6f5d509a42f87f5165d6a70e5c6 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 11:30:27 -0600 Subject: [PATCH 163/212] Fix two broken links in user's guide --- docs/source/usersguide/beginners.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/usersguide/beginners.rst b/docs/source/usersguide/beginners.rst index 22b09a24d3..ec37d0825a 100644 --- a/docs/source/usersguide/beginners.rst +++ b/docs/source/usersguide/beginners.rst @@ -151,8 +151,8 @@ and `Volume II`_. You may also find it helpful to review the following terms: .. _git: http://git-scm.com/ .. _git tutorials: http://git-scm.com/documentation .. _Reactor Concepts Manual: http://www.tayloredge.com/periodic/trivia/ReactorConcepts.pdf -.. _Volume I: http://energy.gov/sites/prod/files/2013/06/f2/h1019v1.pdf -.. _Volume II: http://energy.gov/sites/prod/files/2013/06/f2/h1019v2.pdf +.. _Volume I: https://www.standards.doe.gov/standards-documents/1000/1019-bhdbk-1993-v1 +.. _Volume II: https://www.standards.doe.gov/standards-documents/1000/1019-bhdbk-1993-v2 .. _OpenMC source code: https://github.com/mit-crpg/openmc .. _GitHub: https://github.com/ .. _bug reports: https://github.com/mit-crpg/openmc/issues From 92697ec06eae659cfd3a801d7bca52efee81cb2d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 21 Feb 2018 15:36:27 -0600 Subject: [PATCH 164/212] Introduce ResultsList class to replace scattered functions --- docs/source/pythonapi/deplete.rst | 2 +- openmc/deplete/__init__.py | 2 +- openmc/deplete/integrator/__init__.py | 1 - openmc/deplete/integrator/cecm.py | 16 +-- openmc/deplete/integrator/predictor.py | 12 +- openmc/deplete/integrator/save_results.py | 42 ------- openmc/deplete/results.py | 93 +++++++++------- openmc/deplete/results_list.py | 105 ++++++++++++++++++ openmc/deplete/utilities.py | 101 ----------------- tests/dummy_operator.py | 42 ++++--- tests/regression_tests/test_deplete_full.py | 10 +- tests/unit_tests/test_deplete_cecm.py | 8 +- tests/unit_tests/test_deplete_integrator.py | 12 +- tests/unit_tests/test_deplete_predictor.py | 8 +- .../test_deplete_resultslist.py} | 28 ++--- 15 files changed, 220 insertions(+), 262 deletions(-) delete mode 100644 openmc/deplete/integrator/save_results.py create mode 100644 openmc/deplete/results_list.py delete mode 100644 openmc/deplete/utilities.py rename tests/{regression_tests/test_deplete_utilities.py => unit_tests/test_deplete_resultslist.py} (62%) diff --git a/docs/source/pythonapi/deplete.rst b/docs/source/pythonapi/deplete.rst index 1d1a1c0ee5..61c5dd18c4 100644 --- a/docs/source/pythonapi/deplete.rst +++ b/docs/source/pythonapi/deplete.rst @@ -59,6 +59,7 @@ data, such as number densities and reaction rates for each material. OperatorResult ReactionRates Results + ResultsList TransportOperator Each of the integrator functions also relies on a number of "helper" functions @@ -71,4 +72,3 @@ as follows: integrator.CRAM16 integrator.CRAM48 - integrator.save_results diff --git a/openmc/deplete/__init__.py b/openmc/deplete/__init__.py index 33b6d9af14..e49c4e69cf 100644 --- a/openmc/deplete/__init__.py +++ b/openmc/deplete/__init__.py @@ -20,5 +20,5 @@ from .operator import * from .reaction_rates import * from .abc import * from .results import * +from .results_list import * from .integrator import * -from .utilities import * diff --git a/openmc/deplete/integrator/__init__.py b/openmc/deplete/integrator/__init__.py index 607650dc69..cf8caffdfe 100644 --- a/openmc/deplete/integrator/__init__.py +++ b/openmc/deplete/integrator/__init__.py @@ -8,4 +8,3 @@ The integrator subcomponents. from .cecm import * from .cram import * from .predictor import * -from .save_results import * diff --git a/openmc/deplete/integrator/cecm.py b/openmc/deplete/integrator/cecm.py index 9a07cd198f..61b58d0b95 100644 --- a/openmc/deplete/integrator/cecm.py +++ b/openmc/deplete/integrator/cecm.py @@ -4,7 +4,7 @@ import copy from collections.abc import Iterable from .cram import deplete -from .save_results import save_results +from ..results import Results def cecm(operator, timesteps, power, print_out=True): @@ -51,20 +51,20 @@ def cecm(operator, timesteps, power, print_out=True): for i, (dt, p) in enumerate(zip(timesteps, power)): # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - results = [operator(x[0], p)] + op_results = [operator(x[0], p)] # Deplete for first half of timestep - x_middle = deplete(chain, x[0], results[0], dt/2, print_out) + x_middle = deplete(chain, x[0], op_results[0], dt/2, print_out) # Get middle-of-timestep reaction rates x.append(x_middle) - results.append(operator(x_middle, p)) + op_results.append(operator(x_middle, p)) # Deplete for full timestep using beginning-of-step materials - x_end = deplete(chain, x[0], results[1], dt, print_out) + x_end = deplete(chain, x[0], op_results[1], dt, print_out) # Create results, write to disk - save_results(operator, x, results, [t, t + dt], i) + Results.save(operator, x, op_results, [t, t + dt], i) # Advance time, update vector t += dt @@ -72,7 +72,7 @@ def cecm(operator, timesteps, power, print_out=True): # Perform one last simulation x = [copy.deepcopy(vec)] - results = [operator(x[0], power[-1])] + op_results = [operator(x[0], power[-1])] # Create results, write to disk - save_results(operator, x, results, [t, t], len(timesteps)) + Results.save(operator, x, op_results, [t, t], len(timesteps)) diff --git a/openmc/deplete/integrator/predictor.py b/openmc/deplete/integrator/predictor.py index 444ca7baa7..9be992c16a 100644 --- a/openmc/deplete/integrator/predictor.py +++ b/openmc/deplete/integrator/predictor.py @@ -4,7 +4,7 @@ import copy from collections.abc import Iterable from .cram import deplete -from .save_results import save_results +from ..results import Results def predictor(operator, timesteps, power, print_out=True): @@ -46,13 +46,13 @@ def predictor(operator, timesteps, power, print_out=True): for i, (dt, p) in enumerate(zip(timesteps, power)): # Get beginning-of-timestep reaction rates x = [copy.deepcopy(vec)] - results = [operator(x[0], p)] + op_results = [operator(x[0], p)] # Create results, write to disk - save_results(operator, x, results, [t, t + dt], i) + Results.save(operator, x, op_results, [t, t + dt], i) # Deplete for full timestep - x_end = deplete(chain, x[0], results[0], dt, print_out) + x_end = deplete(chain, x[0], op_results[0], dt, print_out) # Advance time, update vector t += dt @@ -60,7 +60,7 @@ def predictor(operator, timesteps, power, print_out=True): # Perform one last simulation x = [copy.deepcopy(vec)] - results = [operator(x[0], power[-1])] + op_results = [operator(x[0], power[-1])] # Create results, write to disk - save_results(operator, x, results, [t, t], len(timesteps)) + Results.save(operator, x, op_results, [t, t], len(timesteps)) diff --git a/openmc/deplete/integrator/save_results.py b/openmc/deplete/integrator/save_results.py deleted file mode 100644 index 98245fdeae..0000000000 --- a/openmc/deplete/integrator/save_results.py +++ /dev/null @@ -1,42 +0,0 @@ -""" Generic result saving code for integrators. - -""" -from ..results import Results, write_results - - -def save_results(op, x, op_results, t, step_ind): - """Creates and writes depletion results to disk - - Parameters - ---------- - op : openmc.deplete.TransportOperator - The operator used to generate these results. - x : list of list of numpy.array - The prior x vectors. Indexed [i][cell] using the above equation. - op_results : list of openmc.deplete.OperatorResult - Results of applying transport operator - t : list of float - Time indices. - step_ind : int - Step index. - - """ - # Get indexing terms - vol_dict, nuc_list, burn_list, full_burn_list = op.get_results_info() - - # Create results - stages = len(x) - results = Results() - results.allocate(vol_dict, nuc_list, burn_list, full_burn_list, stages) - - n_mat = len(burn_list) - - for i in range(stages): - for mat_i in range(n_mat): - results[i, mat_i, :] = x[i][mat_i][:] - - results.k = [r.k for r in op_results] - results.rates = [r.rates for r in op_results] - results.time = t - - write_results(results, "depletion_results.h5", step_ind) diff --git a/openmc/deplete/results.py b/openmc/deplete/results.py index b7e5623c7d..ab740e61ec 100644 --- a/openmc/deplete/results.py +++ b/openmc/deplete/results.py @@ -11,7 +11,6 @@ import h5py from . import comm, have_mpi from .reaction_rates import ReactionRates -from openmc.checkvalue import check_filetype_version _VERSION_RESULTS = (1, 0) @@ -146,6 +145,27 @@ class Results(object): # Create storage array self.data = np.zeros((stages, self.n_mat, self.n_nuc)) + def export_to_hdf5(self, filename, step): + """Export results to an HDF5 file + + Parameters + ---------- + filename : str + The filename to write to + step : int + What step is this? + + """ + if have_mpi and h5py.get_config().mpi: + kwargs = {'driver': 'mpio', 'comm': comm} + else: + kwargs = {} + + kwargs['mode'] = "w" if step == 0 else "a" + + with h5py.File(filename, **kwargs) as handle: + self._to_hdf5(handle, step) + def _write_hdf5_metadata(self, handle): """Writes result metadata in HDF5 file @@ -217,7 +237,7 @@ class Results(object): handle.create_dataset("time", (1, 2), maxshape=(None, 2), dtype='float64') - def to_hdf5(self, handle, index): + def _to_hdf5(self, handle, index): """Converts results object into an hdf5 object. Parameters @@ -338,49 +358,40 @@ class Results(object): return results + @staticmethod + def save(op, x, op_results, t, step_ind): + """Creates and writes depletion results to disk -def write_results(result, filename, step): - """Outputs result to an HDF5 file. + Parameters + ---------- + op : openmc.deplete.TransportOperator + The operator used to generate these results. + x : list of list of numpy.array + The prior x vectors. Indexed [i][cell] using the above equation. + op_results : list of openmc.deplete.OperatorResult + Results of applying transport operator + t : list of float + Time indices. + step_ind : int + Step index. - Parameters - ---------- - result : Results - Object to be stored in a file. - filename : String - Target filename. - step : int - What step is this? + """ + # Get indexing terms + vol_dict, nuc_list, burn_list, full_burn_list = op.get_results_info() - """ - if have_mpi and h5py.get_config().mpi: - kwargs = {'driver': 'mpio', 'comm': comm} - else: - kwargs = {} + # Create results + stages = len(x) + results = Results() + results.allocate(vol_dict, nuc_list, burn_list, full_burn_list, stages) - kwargs['mode'] = "w" if step == 0 else "a" + n_mat = len(burn_list) - with h5py.File(filename, **kwargs) as handle: - result.to_hdf5(handle, step) + for i in range(stages): + for mat_i in range(n_mat): + results[i, mat_i, :] = x[i][mat_i][:] + results.k = [r.k for r in op_results] + results.rates = [r.rates for r in op_results] + results.time = t -def read_results(filename): - """Return a list of Results objects from an HDF5 file. - - Parameters - ---------- - filename : str - The filename to read from. - - Returns - ------- - results : list of openmc.deplete.Results - The result objects. - - """ - with h5py.File(str(filename), "r") as fh: - check_filetype_version(fh, 'depletion results', _VERSION_RESULTS[0]) - - # Get number of results stored - n = fh["number"].value.shape[0] - - return [Results.from_hdf5(fh, i) for i in range(n)] + results.export_to_hdf5("depletion_results.h5", step_ind) diff --git a/openmc/deplete/results_list.py b/openmc/deplete/results_list.py new file mode 100644 index 0000000000..d3d45e955b --- /dev/null +++ b/openmc/deplete/results_list.py @@ -0,0 +1,105 @@ +import h5py +import numpy as np + +from .results import Results, _VERSION_RESULTS +from openmc.checkvalue import check_filetype_version + + +class ResultsList(list): + """A list of openmc.deplete.Results objects + + Parameters + ---------- + filename : str + The filename to read from. + + """ + def __init__(self, filename): + super().__init__() + with h5py.File(str(filename), "r") as fh: + check_filetype_version(fh, 'depletion results', _VERSION_RESULTS[0]) + + # Get number of results stored + n = fh["number"].value.shape[0] + + for i in range(n): + self.append(Results.from_hdf5(fh, i)) + + def get_atoms(self, mat, nuc): + """Get nuclide concentration over time from a single material + + Parameters + ---------- + mat : str + Material name to evaluate + nuc : str + Nuclide name to evaluate + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + concentration : numpy.ndarray + Total number of atoms for specified nuclide + + """ + time = np.empty_like(self) + concentration = np.empty_like(self) + + # Evaluate value in each region + for i, result in enumerate(self): + time[i] = result.time[0] + concentration[i] = result[0, mat, nuc] + + return time, concentration + + def get_reaction_rate(self, mat, nuc, rx): + """Get reaction rate in a single material/nuclide over time + + Parameters + ---------- + mat : str + Material name to evaluate + nuc : str + Nuclide name to evaluate + rx : str + Reaction rate to evaluate + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + rate : numpy.ndarray + Array of reaction rates + + """ + time = np.empty_like(self) + rate = np.empty_like(self) + + # Evaluate value in each region + for i, result in enumerate(self): + time[i] = result.time[0] + rate[i] = result.rates[0].get(mat, nuc, rx) * result[0, mat, nuc] + + return time, rate + + def get_eigenvalue(self): + """Evaluates the eigenvalue from a results list. + + Returns + ------- + time : numpy.ndarray + Array of times in [s] + eigenvalue : numpy.ndarray + k-eigenvalue at each time + + """ + time = np.empty_like(self) + eigenvalue = np.empty_like(self) + + # Get time/eigenvalue at each point + for i, result in enumerate(self): + time[i] = result.time[0] + eigenvalue[i] = result.k[0] + + return time, eigenvalue diff --git a/openmc/deplete/utilities.py b/openmc/deplete/utilities.py deleted file mode 100644 index 59d5305465..0000000000 --- a/openmc/deplete/utilities.py +++ /dev/null @@ -1,101 +0,0 @@ -"""The utilities module. - -Contains functions that can be used to post-process objects that come out of -the results module. -""" - -import numpy as np - - -def evaluate_single_nuclide(results, mat, nuc): - """Evaluates a single nuclide in a single material from a results list. - - Parameters - ---------- - results : list of results - The results to extract data from. Must be sorted and continuous. - mat : str - Material name to evaluate - nuc : str - Nuclide name to evaluate - - Returns - ------- - time : numpy.ndarray - Time vector - concentration : numpy.ndarray - Total number of atoms in the material - - """ - n_points = len(results) - time = np.zeros(n_points) - concentration = np.zeros(n_points) - - # Evaluate value in each region - for i, result in enumerate(results): - time[i] = result.time[0] - concentration[i] = result[0, mat, nuc] - - return time, concentration - - -def evaluate_reaction_rate(results, mat, nuc, rx): - """Return reaction rate in a single material/nuclide from a results list. - - Parameters - ---------- - results : list of openmc.deplete.Results - The results to extract data from. Must be sorted and continuous. - mat : str - Material name to evaluate - nuc : str - Nuclide name to evaluate - rx : str - Reaction rate to evaluate - - Returns - ------- - time : numpy.ndarray - Time vector. - rate : numpy.ndarray - Reaction rate. - - """ - n_points = len(results) - time = np.zeros(n_points) - rate = np.zeros(n_points) - # Evaluate value in each region - for i, result in enumerate(results): - time[i] = result.time[0] - rate[i] = result.rates[0].get(mat, nuc, rx) * result[0, mat, nuc] - - return time, rate - - -def evaluate_eigenvalue(results): - """Evaluates the eigenvalue from a results list. - - Parameters - ---------- - results : list of openmc.deplete.Results - The results to extract data from. Must be sorted and continuous. - - Returns - ------- - time : numpy.ndarray - Time vector. - eigenvalue : numpy.ndarray - Eigenvalue. - - """ - n_points = len(results) - time = np.zeros(n_points) - eigenvalue = np.zeros(n_points) - - # Evaluate value in each region - for i, result in enumerate(results): - - time[i] = result.time[0] - eigenvalue[i] = result.k[0] - - return time, eigenvalue diff --git a/tests/dummy_operator.py b/tests/dummy_operator.py index 706793d93f..05fe97a950 100644 --- a/tests/dummy_operator.py +++ b/tests/dummy_operator.py @@ -34,19 +34,15 @@ class DummyOperator(TransportOperator): Returns ------- - k : float - Zero. - rates : ReactionRates - Reaction rates from this simulation. - seed : int - Zero. + openmc.deplete.OperatorResult + Result of transport operator + """ + mats = ["1"] + nuclides = ["1", "2"] + reactions = ["1"] - cell_to_ind = {"1" : 0} - nuc_to_ind = {"1" : 0, "2" : 1} - react_to_ind = {"1" : 0} - - reaction_rates = ReactionRates(cell_to_ind, nuc_to_ind, react_to_ind) + reaction_rates = ReactionRates(mats, nuclides, reactions) reaction_rates[0, 0, 0] = vec[0][0] reaction_rates[0, 1, 0] = vec[0][1] @@ -105,18 +101,18 @@ class DummyOperator(TransportOperator): return ["1", "2"] @property - def burn_list(self): + def local_mats(self): """ - burn_list : list of str - A list of all cell IDs to be burned. Used for sorting the simulation. + local_mats : list of str + A list of all material IDs to be burned. Used for sorting the simulation. """ return ["1"] @property - def mat_tally_ind(self): + def burnable_mats(self): """Maps cell name to index in global geometry.""" - return {"1": 0} + return self.local_mats @property @@ -125,11 +121,11 @@ class DummyOperator(TransportOperator): reaction_rates : ReactionRates Reaction rates from the last operator step. """ - cell_to_ind = {"1" : 0} - nuc_to_ind = {"1" : 0, "2" : 1} - react_to_ind = {"1" : 0} + mats = ["1"] + nuclides = ["1", "2"] + reactions = ["1"] - return ReactionRates(cell_to_ind, nuc_to_ind, react_to_ind) + return ReactionRates(mats, nuclides, reactions) def initial_condition(self): """Returns initial vector. @@ -153,8 +149,8 @@ class DummyOperator(TransportOperator): A list of all nuclide names. Used for sorting the simulation. burn_list : list of int A list of all cell IDs to be burned. Used for sorting the simulation. - full_burn_dict : OrderedDict of str to int + full_burn_list : OrderedDict of str to int Maps cell name to index in global geometry. - """ - return self.volume, self.nuc_list, self.burn_list, self.mat_tally_ind + """ + return self.volume, self.nuc_list, self.local_mats, self.burnable_mats diff --git a/tests/regression_tests/test_deplete_full.py b/tests/regression_tests/test_deplete_full.py index fb31ac0c03..19e2c7664b 100644 --- a/tests/regression_tests/test_deplete_full.py +++ b/tests/regression_tests/test_deplete_full.py @@ -8,8 +8,6 @@ import numpy as np import openmc from openmc.data import JOULE_PER_EV import openmc.deplete -from openmc.deplete import results -from openmc.deplete import utilities from tests.regression_tests import config from .example_geometry import generate_problem @@ -67,8 +65,8 @@ def test_full(run_in_tmpdir): return # Load the reference/test results - res_test = results.read_results(path_test) - res_ref = results.read_results(path_reference) + res_test = openmc.deplete.ResultsList(path_test) + res_ref = openmc.deplete.ResultsList(path_reference) # Assert same mats for mat in res_ref[0].mat_to_ind: @@ -88,8 +86,8 @@ def test_full(run_in_tmpdir): tol = 1.0e-6 for mat in res_test[0].mat_to_ind: for nuc in res_test[0].nuc_to_ind: - _, y_test = utilities.evaluate_single_nuclide(res_test, mat, nuc) - _, y_old = utilities.evaluate_single_nuclide(res_ref, mat, nuc) + _, y_test = res_test.get_atoms(mat, nuc) + _, y_old = res_ref.get_atoms(mat, nuc) # Test each point correct = True diff --git a/tests/unit_tests/test_deplete_cecm.py b/tests/unit_tests/test_deplete_cecm.py index 6deb6cd3dd..466a2eec74 100644 --- a/tests/unit_tests/test_deplete_cecm.py +++ b/tests/unit_tests/test_deplete_cecm.py @@ -5,8 +5,6 @@ These tests integrate a simple test problem described in dummy_geometry.py. from pytest import approx import openmc.deplete -from openmc.deplete import results -from openmc.deplete import utilities from tests import dummy_operator @@ -23,10 +21,10 @@ def test_cecm(run_in_tmpdir): openmc.deplete.cecm(op, dt, power, print_out=False) # Load the files - res = results.read_results(op.output_dir / "depletion_results.h5") + res = openmc.deplete.ResultsList(op.output_dir / "depletion_results.h5") - _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") - _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") + _, y1 = res.get_atoms("1", "1") + _, y2 = res.get_atoms("1", "2") # Mathematica solution s1 = [1.86872629872102, 1.395525772416039] diff --git a/tests/unit_tests/test_deplete_integrator.py b/tests/unit_tests/test_deplete_integrator.py index b209900889..a1768625b2 100644 --- a/tests/unit_tests/test_deplete_integrator.py +++ b/tests/unit_tests/test_deplete_integrator.py @@ -1,4 +1,4 @@ -"""Tests for integrator.py +"""Tests for saving results It is worth noting that openmc.deplete.integrate is extremely complex, to the point I am unsure if it can be reasonably unit-tested. For the time being, it @@ -11,11 +11,11 @@ import os from unittest.mock import MagicMock import numpy as np -from openmc.deplete import (integrator, ReactionRates, results, comm, +from openmc.deplete import (ReactionRates, Results, ResultsList, comm, OperatorResult) -def test_save_results(run_in_tmpdir): +def test_results_save(run_in_tmpdir): """Test data save module""" stages = 3 @@ -72,11 +72,11 @@ def test_save_results(run_in_tmpdir): op_result1 = [OperatorResult(k, rates) for k, rates in zip(eigvl1, rate1)] op_result2 = [OperatorResult(k, rates) for k, rates in zip(eigvl2, rate2)] - integrator.save_results(op, x1, op_result1, t1, 0) - integrator.save_results(op, x2, op_result2, t2, 1) + Results.save(op, x1, op_result1, t1, 0) + Results.save(op, x2, op_result2, t2, 1) # Load the files - res = results.read_results("depletion_results.h5") + res = ResultsList("depletion_results.h5") for i in range(stages): for mat_i, mat in enumerate(burn_list): diff --git a/tests/unit_tests/test_deplete_predictor.py b/tests/unit_tests/test_deplete_predictor.py index 0d283855cb..50803e5085 100644 --- a/tests/unit_tests/test_deplete_predictor.py +++ b/tests/unit_tests/test_deplete_predictor.py @@ -5,8 +5,6 @@ These tests integrate a simple test problem described in dummy_geometry.py. from pytest import approx import openmc.deplete -from openmc.deplete import results -from openmc.deplete import utilities from tests import dummy_operator @@ -23,10 +21,10 @@ def test_predictor(run_in_tmpdir): openmc.deplete.predictor(op, dt, power, print_out=False) # Load the files - res = results.read_results(op.output_dir / "depletion_results.h5") + res = openmc.deplete.ResultsList(op.output_dir / "depletion_results.h5") - _, y1 = utilities.evaluate_single_nuclide(res, "1", "1") - _, y2 = utilities.evaluate_single_nuclide(res, "1", "2") + _, y1 = res.get_atoms("1", "1") + _, y2 = res.get_atoms("1", "2") # Mathematica solution s1 = [2.46847546272295, 0.986431226850467] diff --git a/tests/regression_tests/test_deplete_utilities.py b/tests/unit_tests/test_deplete_resultslist.py similarity index 62% rename from tests/regression_tests/test_deplete_utilities.py rename to tests/unit_tests/test_deplete_resultslist.py index 82d4d56a4c..aad8cd9f68 100644 --- a/tests/regression_tests/test_deplete_utilities.py +++ b/tests/unit_tests/test_deplete_resultslist.py @@ -1,26 +1,22 @@ -""" Tests the utilities classes. - -This also tests the results read/write code. -""" +"""Tests the ResultsList class""" from pathlib import Path import numpy as np import pytest -from openmc.deplete import results -from openmc.deplete import utilities +import openmc.deplete @pytest.fixture def res(): """Load the reference results""" - filename = Path(__file__).with_name('test_reference.h5') - return results.read_results(filename) + filename = Path(__file__).parents[1] / 'regression_tests' / 'test_reference.h5' + return openmc.deplete.ResultsList(filename) -def test_evaluate_single_nuclide(res): - """Tests evaluating single nuclide utility code.""" - t, n = utilities.evaluate_single_nuclide(res, "1", "Xe135") +def test_get_atoms(res): + """Tests evaluating single nuclide concentration.""" + t, n = res.get_atoms("1", "Xe135") t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] n_ref = [6.6747328233649218e+08, 3.5421791038348462e+14, @@ -29,9 +25,9 @@ def test_evaluate_single_nuclide(res): np.testing.assert_array_equal(t, t_ref) np.testing.assert_array_equal(n, n_ref) -def test_evaluate_reaction_rate(res): - """Tests evaluating reaction rate utility code.""" - t, r = utilities.evaluate_reaction_rate(res, "1", "Xe135", "(n,gamma)") +def test_get_reaction_rate(res): + """Tests evaluating reaction rate.""" + t, r = res.get_reaction_rate("1", "Xe135", "(n,gamma)") t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] n_ref = np.array([6.6747328233649218e+08, 3.5421791038348462e+14, @@ -43,9 +39,9 @@ def test_evaluate_reaction_rate(res): np.testing.assert_array_equal(r, n_ref * xs_ref) -def test_evaluate_eigenvalue(res): +def test_get_eigenvalue(res): """Tests evaluating eigenvalue.""" - t, k = utilities.evaluate_eigenvalue(res) + t, k = res.get_eigenvalue() t_ref = [0.0, 1296000.0, 2592000.0, 3888000.0] k_ref = [1.181281798790367, 1.1798750921988739, 1.1965943696058159, From 7622a1a39472a64fac950930423b6bedd2b8ff9a Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 22 Feb 2018 16:00:32 -0600 Subject: [PATCH 165/212] Add methods on Material to get mass (if volume specified) --- docs/source/pythonapi/data.rst | 1 + openmc/data/data.py | 20 ++++++++++ openmc/deplete/chain.py | 13 +----- openmc/material.py | 64 +++++++++++++++++++++++++++++- tests/unit_tests/test_data_misc.py | 8 ++++ tests/unit_tests/test_material.py | 17 ++++++++ 6 files changed, 110 insertions(+), 13 deletions(-) diff --git a/docs/source/pythonapi/data.rst b/docs/source/pythonapi/data.rst index 3c221906db..52dc5173b0 100644 --- a/docs/source/pythonapi/data.rst +++ b/docs/source/pythonapi/data.rst @@ -36,6 +36,7 @@ Core Functions openmc.data.thin openmc.data.water_density openmc.data.write_compact_458_library + openmc.data.zam Angle-Energy Distributions -------------------------- diff --git a/openmc/data/data.py b/openmc/data/data.py index 523ac9769d..70bc00bd92 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -313,6 +313,26 @@ def water_density(temperature, pressure=0.1013): return coeff / pi / gamma1_pi +def zam(name): + """Return tuple of (atomic number, mass number, metastable state) + + Parameters + ---------- + name : str + Name of nuclide using GND convention, e.g., 'Am242m1' + + Returns + ------- + 3-tuple of int + Atomic number, mass number, and metastable state + + """ + symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', + name).groups() + metastable = int(state[2:]) if state else 0 + return (ATOMIC_NUMBER[symbol], int(A), metastable) + + # Values here are from the Committee on Data for Science and Technology # (CODATA) 2014 recommendation (doi:10.1103/RevModPhys.88.035009). diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 23395329eb..bcef5fff11 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -40,15 +40,6 @@ _REACTIONS = [ ] -def _get_zai(s): - """Get ZAI value (10000*z + 10*A + metastable state) for sorting purposes""" - symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', s).groups() - Z = openmc.data.ATOMIC_NUMBER[symbol] - A = int(A) - state = int(state[2:]) if state else 0 - return 10000*Z + 10*A + state - - def replace_missing(product, decay_data): """Replace missing product with suitable decay daughter. @@ -197,7 +188,7 @@ class Chain(object): missing_fpy = [] missing_fp = [] - for idx, parent in enumerate(sorted(decay_data, key=_get_zai)): + for idx, parent in enumerate(sorted(decay_data, key=openmc.data.zam)): data = decay_data[parent] nuclide = Nuclide() @@ -290,7 +281,7 @@ class Chain(object): missing_fp.append((parent, E, yield_replace)) nuclide.yield_data[E] = [] - for k in sorted(yields, key=_get_zai): + for k in sorted(yields, key=openmc.data.zam): nuclide.yield_data[E].append((k, yields[k])) # Display warnings diff --git a/openmc/material.py b/openmc/material.py index e409d6536c..351e2db272 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -52,8 +52,7 @@ class Material(IDManagerMixin): 'atom/b-cm', 'atom/cm3', 'sum', or 'macro'. The 'macro' unit only applies in the case of a multi-group calculation. depletable : bool - Indicate whether the material is depletable. This attribute can be used - by downstream depletion applications. + Indicate whether the material is depletable. nuclides : list of tuple List in which each item is a 3-tuple consisting of a nuclide string, the percent density, and the percent type ('ao' or 'wo'). @@ -74,6 +73,9 @@ class Material(IDManagerMixin): :meth:`Geometry.determine_paths` method. num_instances : int The number of instances of this material throughout the geometry. + fissionable_mass : float + Mass of fissionable nuclides in the material in [g]. Requires that the + :attr:`volume` attribute is set. """ @@ -245,6 +247,18 @@ class Material(IDManagerMixin): str) self._isotropic = list(isotropic) + @property + def fissionable_mass(self): + if self.volume is None: + raise ValueError("Volume must be set in order to determine mass.") + density = 0.0 + for nuc, atoms_per_cc in self.get_nuclide_atom_densities().values(): + Z = openmc.data.zam(nuc)[0] + if Z >= 90: + density += 1e24 * atoms_per_cc * openmc.data.atomic_mass(nuc) \ + / openmc.data.AVOGADRO + return density*self.volume + @classmethod def from_hdf5(cls, group): """Create material from HDF5 group @@ -687,7 +701,53 @@ class Material(IDManagerMixin): return nuclides + def get_mass_density(self, nuclide=None): + """Return mass density of one or all nuclides + + Parameters + ---------- + nuclides : str, optional + Nuclide for which density is desired. If not specified, the density + for the entire material is given. + + Returns + ------- + float + Density of the nuclide/material in [g/cm^3] + + """ + mass_density = 0.0 + for nuc, atoms_per_cc in self.get_nuclide_atom_densities().values(): + density_i = 1e24 * atoms_per_cc * openmc.data.atomic_mass(nuc) \ + / openmc.data.AVOGADRO + if nuclide is None or nuclide == nuc: + mass_density += density_i + return mass_density + + def get_mass(self, nuclide=None): + """Return mass of one or all nuclides. + + Note that this method requires that the :attr:`Material.volume` has + already been set. + + Parameters + ---------- + nuclides : str, optional + Nuclide for which mass is desired. If not specified, the density + for the entire material is given. + + Returns + ------- + float + Mass of the nuclide/material in [g] + + """ + if self.volume is None: + raise ValueError("Volume must be set in order to determine mass.") + return self.volume*self.get_mass_density(nuclide) + def clone(self, memo=None): + """Create a copy of this material with a new unique ID. Parameters diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index 433d34adb9..7d00b7bc77 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -58,3 +58,11 @@ def test_water_density(): assert dens(300.0, 3.0) == pytest.approx(1e-3/0.100215168e-2, 1e-6) assert dens(300.0, 80.0) == pytest.approx(1e-3/0.971180894e-3, 1e-6) assert dens(500.0, 3.0) == pytest.approx(1e-3/0.120241800e-2, 1e-6) + + +def test_zam(): + assert openmc.data.zam('H1') == (1, 1, 0) + assert openmc.data.zam('Zr90') == (40, 90, 0) + assert openmc.data.zam('Am242') == (95, 242, 0) + assert openmc.data.zam('Am242_m1') == (95, 242, 1) + assert openmc.data.zam('Am242_m10') == (95, 242, 10) diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index 2265215417..c251df3a6d 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -121,6 +121,23 @@ def test_get_nuclide_atom_densities(uo2): assert density > 0 +def test_mass(): + m = openmc.Material() + m.add_nuclide('Zr90', 1.0, 'wo') + m.add_nuclide('U235', 1.0, 'wo') + m.set_density('g/cm3', 2.0) + m.volume = 10.0 + + assert m.get_mass_density('Zr90') == pytest.approx(1.0) + assert m.get_mass_density('U235') == pytest.approx(1.0) + assert m.get_mass_density() == pytest.approx(2.0) + + assert m.get_mass('Zr90') == pytest.approx(10.0) + assert m.get_mass('U235') == pytest.approx(10.0) + assert m.get_mass() == pytest.approx(20.0) + assert m.fissionable_mass == pytest.approx(10.0) + + def test_materials(run_in_tmpdir): m1 = openmc.Material() m1.add_nuclide('U235', 1.0, 'wo') From ab00421c0eda42adb29a90e49e08230cbebaa9a5 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 23 Feb 2018 11:37:55 -0600 Subject: [PATCH 166/212] Add test for Chain.from_endf. Remove tqdm dependence. --- docs/source/conf.py | 2 +- openmc/data/endf.py | 5 +-- openmc/deplete/chain.py | 42 ++++++++++++-------------- setup.py | 2 +- tests/unit_tests/test_deplete_chain.py | 14 +++++++-- 5 files changed, 35 insertions(+), 30 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index a2fec39b75..eeecba23e4 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -26,7 +26,7 @@ MOCK_MODULES = [ 'numpy.ctypeslib', 'scipy', 'scipy.sparse', 'scipy.sparse.linalg', 'scipy.interpolate', 'scipy.integrate', 'scipy.optimize', 'scipy.special', 'scipy.stats', 'scipy.spatial', 'h5py', 'pandas', 'uncertainties', - 'matplotlib', 'matplotlib.pyplot', 'tqdm', 'openmoc', + 'matplotlib', 'matplotlib.pyplot', 'openmoc', 'openmc.data.reconstruct' ] sys.modules.update((mod_name, MagicMock()) for mod_name in MOCK_MODULES) diff --git a/openmc/data/endf.py b/openmc/data/endf.py index 160ab61513..db94e15bea 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -10,6 +10,7 @@ import io import re import os from math import pi +from pathlib import PurePath from collections import OrderedDict from collections.abc import Iterable @@ -299,8 +300,8 @@ class Evaluation(object): """ def __init__(self, filename_or_obj): - if isinstance(filename_or_obj, str): - fh = open(filename_or_obj, 'r') + if isinstance(filename_or_obj, (str, PurePath)): + fh = open(str(filename_or_obj), 'r') else: fh = filename_or_obj self.section = {} diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index bcef5fff11..612ec29cb9 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -20,7 +20,6 @@ try: except ImportError: import xml.etree.ElementTree as ET _have_lxml = False -from tqdm import tqdm import scipy.sparse as sp import openmc.data @@ -153,34 +152,31 @@ class Chain(object): chain = cls() # Create dictionary mapping target to filename + print('Processing neutron sub-library files...') reactions = {} - with tqdm(neutron_files) as pbar: - for f in pbar: - pbar.set_description('Processing {}'.format(os.path.basename(f))) - evaluation = openmc.data.endf.Evaluation(f) - name = evaluation.gnd_name - reactions[name] = {} - for mf, mt, nc, mod in evaluation.reaction_list: - if mf == 3: - file_obj = StringIO(evaluation.section[3, mt]) - openmc.data.endf.get_head_record(file_obj) - q_value = openmc.data.endf.get_cont_record(file_obj)[1] - reactions[name][mt] = q_value + for f in neutron_files: + evaluation = openmc.data.endf.Evaluation(f) + name = evaluation.gnd_name + reactions[name] = {} + for mf, mt, nc, mod in evaluation.reaction_list: + if mf == 3: + file_obj = StringIO(evaluation.section[3, mt]) + openmc.data.endf.get_head_record(file_obj) + q_value = openmc.data.endf.get_cont_record(file_obj)[1] + reactions[name][mt] = q_value # Determine what decay and FPY nuclides are available + print('Processing decay sub-library files...') decay_data = {} - with tqdm(decay_files) as pbar: - for f in pbar: - pbar.set_description('Processing {}'.format(os.path.basename(f))) - data = openmc.data.Decay(f) - decay_data[data.nuclide['name']] = data + for f in decay_files: + data = openmc.data.Decay(f) + decay_data[data.nuclide['name']] = data + print('Processing fission product yield sub-library files...') fpy_data = {} - with tqdm(fpy_files) as pbar: - for f in pbar: - pbar.set_description('Processing {}'.format(os.path.basename(f))) - data = openmc.data.FissionProductYields(f) - fpy_data[data.nuclide['name']] = data + for f in fpy_files: + data = openmc.data.FissionProductYields(f) + fpy_data[data.nuclide['name']] = data print('Creating depletion_chain...') missing_daughter = [] diff --git a/setup.py b/setup.py index ee11f414b6..2a42dd65dd 100755 --- a/setup.py +++ b/setup.py @@ -57,7 +57,7 @@ kwargs = { # Required dependencies 'install_requires': [ 'numpy>=1.9', 'h5py', 'scipy', 'ipython', 'matplotlib', - 'pandas', 'lxml', 'uncertainties', 'tqdm' + 'pandas', 'lxml', 'uncertainties' ], # Optional dependencies diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index f7e7899a30..4ec5415ee9 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -5,11 +5,13 @@ import os from pathlib import Path import numpy as np +from openmc.data import zam, ATOMIC_SYMBOL from openmc.deplete import comm, Chain, reaction_rates, nuclide import pytest from tests import cdtemp +_ENDF_DATA = Path(os.environ['OPENMC_ENDF_DATA']) _TEST_CHAIN = """\ @@ -63,9 +65,15 @@ def test_len(): def test_from_endf(): - """Test depletion chain building from ENDF. Empty at the moment until we figure - out a good way to unit-test this.""" - pass + """Test depletion chain building from ENDF files""" + decay_data = (_ENDF_DATA / 'decay').glob('*.endf') + fpy_data = (_ENDF_DATA / 'nfy').glob('*.endf') + neutron_data = (_ENDF_DATA / 'neutrons').glob('*.endf') + chain = Chain.from_endf(decay_data, fpy_data, neutron_data) + + assert len(chain) == len(chain.nuclides) == len(chain.nuclide_dict) == 3821 + for nuc in chain.nuclides: + assert nuc == chain[nuc.name] def test_from_xml(simple_chain): From fc73f195a520bf39772d86fd8d6260f40c5842fc Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 23 Feb 2018 11:54:16 -0600 Subject: [PATCH 167/212] Mention mpi4py as optional dependency in docs --- docs/source/usersguide/install.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/source/usersguide/install.rst b/docs/source/usersguide/install.rst index 9b11d1dce4..24bcc7164d 100644 --- a/docs/source/usersguide/install.rst +++ b/docs/source/usersguide/install.rst @@ -452,6 +452,11 @@ distributions. .. admonition:: Optional :class: note + `mpi4py `_ + mpi4py provides Python bindings to MPI for running distributed-memory + parallel runs. This package is needed if you plan on running depletion + simulations in parallel using MPI. + `Cython `_ Cython is used for resonance reconstruction for ENDF data converted to :class:`openmc.data.IncidentNeutron`. From 13a167393d9bccb173e0c1e6584cbecf5b6e8ef0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 23 Feb 2018 14:59:13 -0600 Subject: [PATCH 168/212] Add archive destination in CMakeLists.txt for building static --- CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 71934a47cc..d3673df26c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -496,7 +496,8 @@ add_custom_command(TARGET libopenmc POST_BUILD install(TARGETS ${program} libopenmc RUNTIME DESTINATION bin - LIBRARY DESTINATION lib) + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) install(DIRECTORY src/relaxng DESTINATION share/openmc) install(FILES man/man1/openmc.1 DESTINATION share/man/man1) install(FILES LICENSE DESTINATION "share/doc/${program}" RENAME copyright) From 09a63ec3e71734daf1ae88f5be1b286b45396f04 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 24 Feb 2018 15:07:58 -0600 Subject: [PATCH 169/212] Remove blank line that was added --- openmc/material.py | 1 - 1 file changed, 1 deletion(-) diff --git a/openmc/material.py b/openmc/material.py index 351e2db272..5fdcb76894 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -747,7 +747,6 @@ class Material(IDManagerMixin): return self.volume*self.get_mass_density(nuclide) def clone(self, memo=None): - """Create a copy of this material with a new unique ID. Parameters From cc57551bd3746f6e1a26a85f309193031474f27f Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sun, 25 Feb 2018 15:22:30 -0600 Subject: [PATCH 170/212] Fix bug in Model.run() --- openmc/model/model.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/openmc/model/model.py b/openmc/model/model.py index d6e6ddce38..72a2c50dd7 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -209,9 +209,7 @@ class Model(object): """ self.export_to_xml() - return_code = openmc.run(**kwargs) - - assert (return_code == 0), "OpenMC did not execute successfully" + openmc.run(**kwargs) n = self.settings.batches if self.settings.statepoint is not None: From e3d6189cfa163579396377df7a91d0f76a2fc043 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 26 Feb 2018 22:12:14 -0600 Subject: [PATCH 171/212] Make sure Decay.half_life is set, even for stable nuclides --- openmc/data/decay.py | 1 + 1 file changed, 1 insertion(+) diff --git a/openmc/data/decay.py b/openmc/data/decay.py index d83338d028..fa18759396 100644 --- a/openmc/data/decay.py +++ b/openmc/data/decay.py @@ -457,6 +457,7 @@ class Decay(EqualityMixin): items, values = get_list_record(file_obj) self.nuclide['spin'] = items[0] self.nuclide['parity'] = items[1] + self.half_life = ufloat(float('inf'), float('inf')) @property def decay_constant(self): From 5993a59196119db37ec9b7183887055480a26808 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 27 Feb 2018 07:22:27 -0600 Subject: [PATCH 172/212] Address first round of comments on #976 --- docs/source/io_formats/depletion_results.rst | 10 +++++----- docs/source/pythonapi/deplete.rst | 11 +++++++++++ openmc/data/data.py | 8 ++++++-- openmc/deplete/atom_number.py | 2 +- openmc/deplete/chain.py | 9 +++------ tests/unit_tests/test_data_misc.py | 2 ++ 6 files changed, 28 insertions(+), 14 deletions(-) diff --git a/docs/source/io_formats/depletion_results.rst b/docs/source/io_formats/depletion_results.rst index fcbc4fb99b..d35e251469 100644 --- a/docs/source/io_formats/depletion_results.rst +++ b/docs/source/io_formats/depletion_results.rst @@ -12,23 +12,23 @@ The current version of the depletion results file format is 1.0. - **version** (*int[2]*) -- Major and minor version of the statepoint file format. -:Datasets: - **eigenvalues** (*float[][]*) -- k-eigenvalues at each +:Datasets: - **eigenvalues** (*double[][]*) -- k-eigenvalues at each time/stage. This array has shape (number of timesteps, number of stages). - - **number** (*float[][][][]*) -- Total number of atoms. This array + - **number** (*double[][][][]*) -- Total number of atoms. This array has shape (number of timesteps, number of stages, number of materials, number of nuclides). - - **reaction rates** (*float[][][][][]*) -- Reaction rates used to + - **reaction rates** (*double[][][][][]*) -- Reaction rates used to build depletion matrices. This array has shape (number of timesteps, number of stages, number of materials, number of nuclides, number of reactions). - - **time** (*float[][2]*) -- Time in [s] at beginning/end of each + - **time** (*double[][2]*) -- Time in [s] at beginning/end of each step. **/materials//** :Attributes: - **index** (*int*) -- Index used in results for this material - - **volume** (*float*) -- Volume of this material in [cm^3] + - **volume** (*double*) -- Volume of this material in [cm^3] **/nuclides//** diff --git a/docs/source/pythonapi/deplete.rst b/docs/source/pythonapi/deplete.rst index 61c5dd18c4..d4055f0fdf 100644 --- a/docs/source/pythonapi/deplete.rst +++ b/docs/source/pythonapi/deplete.rst @@ -27,6 +27,17 @@ specific to OpenMC is available using the following class: Operator +When running in parallel using `mpi4py `_, the MPI +intercommunicator used can be changed by modifying the following module +variable. If it is not explicitly modified, it defaults to +``mpi4py.MPI.COMM_WORLD``. + +.. data:: comm + + MPI intercommunicator used to call OpenMC library + + :type: mpi4py.MPI.Comm + Internal Classes and Functions ------------------------------ diff --git a/openmc/data/data.py b/openmc/data/data.py index 70bc00bd92..d0bb65648c 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -327,8 +327,12 @@ def zam(name): Atomic number, mass number, and metastable state """ - symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', - name).groups() + try: + symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', + name).groups() + except AttributeError: + raise ValueError("'{}' does not appear to be a nuclide name in GND " + "format.".format(name)) metastable = int(state[2:]) if state else 0 return (ATOMIC_NUMBER[symbol], int(A), metastable) diff --git a/openmc/deplete/atom_number.py b/openmc/deplete/atom_number.py index 9a32dfa3a0..b5357280c0 100644 --- a/openmc/deplete/atom_number.py +++ b/openmc/deplete/atom_number.py @@ -41,7 +41,7 @@ class AtomNumber(object): n_nuc_burn : int Number of burnable nuclides. n_nuc : int - Number of nuclidess. + Number of nuclides. """ def __init__(self, local_mats, nuclides, volume, n_nuc_burn): diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index 612ec29cb9..fbe6792227 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -55,15 +55,12 @@ def replace_missing(product, decay_data): Replacement for missing product in GND format. """ - - symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_m\d+)?)', - product).groups() - Z = openmc.data.ATOMIC_NUMBER[symbol] - A = int(A) + # Determine atomic number, mass number, and metastable state + Z, A, state = openmc.data.zam(product) + symbol = openmc.data.ATOMIC_SYMBOL[Z] # First check if ground state is available if state: - metastable_state = int(state[2:]) product = '{}{}'.format(symbol, A) # Find isotope with longest half-life diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index 7d00b7bc77..6167449268 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -66,3 +66,5 @@ def test_zam(): assert openmc.data.zam('Am242') == (95, 242, 0) assert openmc.data.zam('Am242_m1') == (95, 242, 1) assert openmc.data.zam('Am242_m10') == (95, 242, 10) + with pytest.raises(ValueError): + openmc.data.zam('garbage') From bedf99d2fea7f92b5558119b1ebc4a6602e2c920 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Thu, 1 Mar 2018 15:56:24 -0500 Subject: [PATCH 173/212] remove print_cmfd and change order in which print_batch_keff is called --- src/output.F90 | 16 +++------------- src/simulation.F90 | 8 +++----- 2 files changed, 6 insertions(+), 18 deletions(-) diff --git a/src/output.F90 b/src/output.F90 index 643a28b671..6e21d9143a 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -356,9 +356,9 @@ contains integer :: n ! number of active generations ! Determine overall generation and number of active generations - i = overall_generation() + i = overall_generation() - 1 n = i - n_inactive*gen_per_batch - + ! write out information batch and option independent output write(UNIT=OUTPUT_UNIT, FMT='(2X,A9)', ADVANCE='NO') & trim(to_str(current_batch)) // "/" // trim(to_str(gen_per_batch)) @@ -377,16 +377,6 @@ contains write(UNIT=OUTPUT_UNIT, FMT='(23X)', ADVANCE='NO') end if - end subroutine print_batch_keff - -!=============================================================================== -! PRINT_CMFD displays the CMFD related information to output after CMFD is -! executed. Will print blank line if CMFD is not on, to ensure consistent -! formatting of output columns -!=============================================================================== - - subroutine print_cmfd() - ! write out cmfd keff if it is active and other display info if (cmfd_on) then write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5)', ADVANCE='NO') & @@ -410,7 +400,7 @@ contains ! next line write(UNIT=OUTPUT_UNIT, FMT=*) - end subroutine print_cmfd + end subroutine print_batch_keff !=============================================================================== ! PRINT_PLOT displays selected options for plotting diff --git a/src/simulation.F90 b/src/simulation.F90 index 91c176b995..701cd191b7 100644 --- a/src/simulation.F90 +++ b/src/simulation.F90 @@ -24,8 +24,7 @@ module simulation use nuclide_header, only: micro_xs, n_nuclides use output, only: header, print_columns, & print_batch_keff, print_generation, print_runtime, & - print_results, print_overlap_check, write_tallies, & - print_cmfd + print_results, print_overlap_check, write_tallies use particle_header, only: Particle use random_lcg, only: set_particle_seed use settings @@ -295,8 +294,6 @@ contains if (master .and. verbosity >= 7) then if (current_gen /= gen_per_batch) then call print_generation() - else - call print_batch_keff() end if end if @@ -339,7 +336,8 @@ contains if (run_mode == MODE_EIGENVALUE) then ! Perform CMFD calculation if on if (cmfd_on) call execute_cmfd() - call print_cmfd() + ! Write batch output + if (master .and. verbosity >= 7) call print_batch_keff() end if ! Check_triggers From a21947ff9804f2b6a7e0be376986ff22c99c6722 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Thu, 1 Mar 2018 16:15:53 -0500 Subject: [PATCH 174/212] Remove trailing whitespace 1 --- src/output.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/output.F90 b/src/output.F90 index 6e21d9143a..349d0007ef 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -358,7 +358,7 @@ contains ! Determine overall generation and number of active generations i = overall_generation() - 1 n = i - n_inactive*gen_per_batch - + ! write out information batch and option independent output write(UNIT=OUTPUT_UNIT, FMT='(2X,A9)', ADVANCE='NO') & trim(to_str(current_batch)) // "/" // trim(to_str(gen_per_batch)) From a96a192cd535429d0d38efb148fca60992935ffe Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Thu, 1 Mar 2018 16:34:16 -0500 Subject: [PATCH 175/212] Remove trailing whitespace 2 --- src/output.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/output.F90 b/src/output.F90 index 349d0007ef..908f698141 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -376,7 +376,7 @@ contains else write(UNIT=OUTPUT_UNIT, FMT='(23X)', ADVANCE='NO') end if - + ! write out cmfd keff if it is active and other display info if (cmfd_on) then write(UNIT=OUTPUT_UNIT, FMT='(3X, F8.5)', ADVANCE='NO') & From 7ee08d5280c3195ba74102027f127f6ac18f26cb Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Mar 2018 23:08:43 -0600 Subject: [PATCH 176/212] Add gnd_name function --- docs/source/pythonapi/data.rst | 1 + openmc/data/data.py | 26 +++++++++++++++++++++++++- openmc/data/endf.py | 13 +++++-------- openmc/material.py | 2 +- tests/unit_tests/test_data_misc.py | 8 ++++++++ 5 files changed, 40 insertions(+), 10 deletions(-) diff --git a/docs/source/pythonapi/data.rst b/docs/source/pythonapi/data.rst index 52dc5173b0..7feaa8d608 100644 --- a/docs/source/pythonapi/data.rst +++ b/docs/source/pythonapi/data.rst @@ -32,6 +32,7 @@ Core Functions :template: myfunction.rst openmc.data.atomic_mass + openmc.data.gnd_name openmc.data.linearize openmc.data.thin openmc.data.water_density diff --git a/openmc/data/data.py b/openmc/data/data.py index d0bb65648c..fd13299617 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -313,13 +313,37 @@ def water_density(temperature, pressure=0.1013): return coeff / pi / gamma1_pi +def gnd_name(Z, A, m=0): + """Return nuclide name using GND convention + + Parameters + ---------- + Z : int + Atomic number + A : int + Mass number + m : int, optional + Metastable state + + Returns + ------- + str + Nuclide name in GND convention, e.g., 'Am242_m1' + + """ + if m > 0: + return '{}{}_m{}'.format(ATOMIC_SYMBOL[Z], A, m) + else: + return '{}{}'.format(ATOMIC_SYMBOL[Z], A) + + def zam(name): """Return tuple of (atomic number, mass number, metastable state) Parameters ---------- name : str - Name of nuclide using GND convention, e.g., 'Am242m1' + Name of nuclide using GND convention, e.g., 'Am242_m1' Returns ------- diff --git a/openmc/data/endf.py b/openmc/data/endf.py index db94e15bea..c44c66be0c 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -17,7 +17,7 @@ from collections.abc import Iterable import numpy as np from numpy.polynomial.polynomial import Polynomial -from .data import ATOMIC_SYMBOL +from .data import ATOMIC_SYMBOL, gnd_name from .function import Tabulated1D, INTERPOLATION_SCHEME from openmc.stats.univariate import Uniform, Tabular, Legendre @@ -249,6 +249,7 @@ def get_tab2_record(file_obj): return params, Tabulated2D(breakpoints, interpolation) + def get_evaluations(filename): """Return a list of all evaluations within an ENDF file. @@ -424,13 +425,9 @@ class Evaluation(object): @property def gnd_name(self): - symbol = ATOMIC_SYMBOL[self.target['atomic_number']] - A = self.target['mass_number'] - m = self.target['isomeric_state'] - if m > 0: - return '{}{}_m{}'.format(symbol, A, m) - else: - return '{}{}'.format(symbol, A) + return gnd_name(self.target['atomic_number'], + self.target['mass_number'], + self.target['isomeric_state']) class Tabulated2D(object): diff --git a/openmc/material.py b/openmc/material.py index 5fdcb76894..d52d8a27b4 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -24,7 +24,7 @@ class Material(IDManagerMixin): To create a material, one should create an instance of this class, add nuclides or elements with :meth:`Material.add_nuclide` or `Material.add_element`, respectively, and set the total material density - with `Material.export_to_xml()`. The material can then be assigned to a cell + with `Material.set_density()`. The material can then be assigned to a cell using the :attr:`Cell.fill` attribute. Parameters diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index 6167449268..04ca0f1031 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -60,6 +60,14 @@ def test_water_density(): assert dens(500.0, 3.0) == pytest.approx(1e-3/0.120241800e-2, 1e-6) +def test_gnd_name(): + assert openmc.data.gnd_name(1, 1) == 'H1' + assert openmc.data.gnd_name(40, 90) == ('Zr90') + assert openmc.data.gnd_name(95, 242, 0) == ('Am242') + assert openmc.data.gnd_name(95, 242, 1) == ('Am242_m1') + assert openmc.data.gnd_name(95, 242, 10) == ('Am242_m10') + + def test_zam(): assert openmc.data.zam('H1') == (1, 1, 0) assert openmc.data.zam('Zr90') == (40, 90, 0) From b9ff205090520b718bbec7a26a07fa7d9361374a Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 1 Mar 2018 23:09:10 -0600 Subject: [PATCH 177/212] Don't put free neutron in depletion chain --- openmc/deplete/chain.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/openmc/deplete/chain.py b/openmc/deplete/chain.py index fbe6792227..1826ca9ca0 100644 --- a/openmc/deplete/chain.py +++ b/openmc/deplete/chain.py @@ -59,6 +59,10 @@ def replace_missing(product, decay_data): Z, A, state = openmc.data.zam(product) symbol = openmc.data.ATOMIC_SYMBOL[Z] + # Replace neutron with proton + if Z == 0 and A == 1: + return 'H1' + # First check if ground state is available if state: product = '{}{}'.format(symbol, A) @@ -167,6 +171,9 @@ class Chain(object): decay_data = {} for f in decay_files: data = openmc.data.Decay(f) + # Skip decay data for neutron itself + if data.nuclide['atomic_number'] == 0: + continue decay_data[data.nuclide['name']] = data print('Processing fission product yield sub-library files...') From efb264da605b1b818e1e62b62decdbe10e8fa03d Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 06:20:16 -0600 Subject: [PATCH 178/212] Fix depletion chain unit test --- tests/unit_tests/test_deplete_chain.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit_tests/test_deplete_chain.py b/tests/unit_tests/test_deplete_chain.py index 4ec5415ee9..1fe83ad98a 100644 --- a/tests/unit_tests/test_deplete_chain.py +++ b/tests/unit_tests/test_deplete_chain.py @@ -71,7 +71,7 @@ def test_from_endf(): neutron_data = (_ENDF_DATA / 'neutrons').glob('*.endf') chain = Chain.from_endf(decay_data, fpy_data, neutron_data) - assert len(chain) == len(chain.nuclides) == len(chain.nuclide_dict) == 3821 + assert len(chain) == len(chain.nuclides) == len(chain.nuclide_dict) == 3820 for nuc in chain.nuclides: assert nuc == chain[nuc.name] From 3120e15ad45aa203607705132f914169f1282b1b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 5 Mar 2018 19:57:34 -0600 Subject: [PATCH 179/212] Avoid segfault when nuclide is present in material that's not used --- src/input_xml.F90 | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 34a2fdd718..8c3669b2e0 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -4265,12 +4265,16 @@ contains ! Show which nuclide results in lowest energy for neutron transport do i = 1, size(nuclides) - if (nuclides(i) % grid(1) % energy(size(nuclides(i) % grid(1) % energy)) & - == energy_max_neutron) then - call write_message("Maximum neutron transport energy: " // & - trim(to_str(energy_max_neutron)) // " eV for " // & - trim(adjustl(nuclides(i) % name)), 7) - exit + ! If a nuclide is present in a material that's not used in the model, its + ! grid has not been allocated + if (size(nuclides(i) % grid) > 0) then + if (nuclides(i) % grid(1) % energy(size(nuclides(i) % grid(1) % energy)) & + == energy_max_neutron) then + call write_message("Maximum neutron transport energy: " // & + trim(to_str(energy_max_neutron)) // " eV for " // & + trim(adjustl(nuclides(i) % name)), 7) + exit + end if end if end do From 3a90b147be78d57e0e795336740eb183295589e3 Mon Sep 17 00:00:00 2001 From: Shikhar Kumar Date: Mon, 5 Mar 2018 22:40:16 -0500 Subject: [PATCH 180/212] redefine i as current_batch*gen_per_batch --- src/output.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/output.F90 b/src/output.F90 index 908f698141..25cb84d58c 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -356,7 +356,7 @@ contains integer :: n ! number of active generations ! Determine overall generation and number of active generations - i = overall_generation() - 1 + i = current_batch*gen_per_batch n = i - n_inactive*gen_per_batch ! write out information batch and option independent output From 80959dc82bb0f3ba5a8b0f592eb8191721e7c410 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 13:53:07 -0400 Subject: [PATCH 181/212] Dont import capi (through model) on import openmc --- openmc/model/model.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/openmc/model/model.py b/openmc/model/model.py index 72a2c50dd7..cd51533217 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -1,11 +1,7 @@ from collections.abc import Iterable import openmc -from openmc.checkvalue import check_type -import openmc.deplete as dep - -_DEPLETE_METHODS = {'predictor': dep.integrator.predictor, - 'cecm': dep.integrator.cecm} +from openmc.checkvalue import check_type, check_value class Model(object): @@ -140,7 +136,8 @@ class Model(object): for plot in plots: self._plots.append(plot) - def deplete(self, timesteps, power, chain_file=None, method='cecm', **kwargs): + def deplete(self, timesteps, power, chain_file=None, method='cecm', + **kwargs): """Deplete model using specified timesteps/power Parameters @@ -164,11 +161,21 @@ class Model(object): :func:`openmc.deplete.integrator.cecm`) """ + # Import the depletion module. This is done here rather than the module + # header to delay importing openmc.capi (through openmc.deplete) which + # can be tough to install properly. + import openmc.deplete as dep + # Create OpenMC transport operator op = dep.Operator(self.geometry, self.settings, chain_file) # Perform depletion - _DEPLETE_METHODS[method](op, timesteps, power, **kwargs) + if method == 'predictor': + dep.integrator.predictor(op, timesteps, power, **kwargs) + elif method == 'cecm': + dep.integrator.cecm(op, timesteps, power, **kwargs) + else: + check_value('method', method, ('cecm', 'predictor')) def export_to_xml(self): """Export model to XML files.""" From 7bb066bc9aab65992055667ac2e641cd708c3203 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 17:15:58 -0400 Subject: [PATCH 182/212] Infer WMP vales like num_l and fissionable --- openmc/data/multipole.py | 123 ++++++++++++++++++--------------------- 1 file changed, 57 insertions(+), 66 deletions(-) diff --git a/openmc/data/multipole.py b/openmc/data/multipole.py index 33078f5046..fd5bf28b3b 100644 --- a/openmc/data/multipole.py +++ b/openmc/data/multipole.py @@ -24,7 +24,7 @@ _RM_RF = 3 # Residue fission # Multi-level Breit Wigner indices _MLBW_RT = 1 # Residue total -_MLBW_RX = 2 # Residue compettitive +_MLBW_RX = 2 # Residue competitive _MLBW_RA = 3 # Residue absorption _MLBW_RF = 4 # Residue fission @@ -141,6 +141,12 @@ def _broaden_wmp_polynomials(E, dopp, n): class WindowedMultipole(EqualityMixin): """Resonant cross sections represented in the windowed multipole format. + Parameters + ---------- + formalism : {'MLBW', 'RM'} + The R-matrix formalism used to reconstruct resonances. Either 'MLBW' + for multi-level Breit Wigner or 'RM' for Reich-Moore. + Attributes ---------- num_l : Integral @@ -195,11 +201,9 @@ class WindowedMultipole(EqualityMixin): a/E + b/sqrt(E) + c + d sqrt(E) + ... """ - def __init__(self): - self.num_l = None - self.fit_order = None - self.fissionable = None - self.formalism = None + def __init__(self, formalism): + self._num_l = None + self.formalism = formalism self.spacing = None self.sqrtAWR = None self.start_E = None @@ -218,11 +222,15 @@ class WindowedMultipole(EqualityMixin): @property def fit_order(self): - return self._fit_order + return self.curvefit.shape[1] - 1 @property def fissionable(self): - return self._fissionable + if self.formalism == 'RM': + return self.data.shape[1] == 4 + else: + # Assume self.formalism == 'MLBW' + return self.data.shape[1] == 5 @property def formalism(self): @@ -272,35 +280,10 @@ class WindowedMultipole(EqualityMixin): def curvefit(self): return self._curvefit - @num_l.setter - def num_l(self, num_l): - if num_l is not None: - cv.check_type('num_l', num_l, Integral) - cv.check_greater_than('num_l', num_l, 1, equality=True) - cv.check_less_than('num_l', num_l, 4, equality=True) - # There is an if block in _evaluate that assumes num_l <= 4. - self._num_l = num_l - - @fit_order.setter - def fit_order(self, fit_order): - if fit_order is not None: - cv.check_type('fit_order', fit_order, Integral) - cv.check_greater_than('fit_order', fit_order, 2, equality=True) - # _broaden_wmp_polynomials assumes the curve fit has at least 3 - # terms. - self._fit_order = fit_order - - @fissionable.setter - def fissionable(self, fissionable): - if fissionable is not None: - cv.check_type('fissionable', fissionable, bool) - self._fissionable = fissionable - @formalism.setter def formalism(self, formalism): - if formalism is not None: - cv.check_type('formalism', formalism, str) - cv.check_value('formalism', formalism, ('MLBW', 'RM')) + cv.check_type('formalism', formalism, str) + cv.check_value('formalism', formalism, ('MLBW', 'RM')) self._formalism = formalism @spacing.setter @@ -337,9 +320,20 @@ class WindowedMultipole(EqualityMixin): cv.check_type('data', data, np.ndarray) if len(data.shape) != 2: raise ValueError('Multipole data arrays must be 2D') - if data.shape[1] not in (3, 4, 5): # 3 or 4 for RM, 4 or 5 for MLBW - raise ValueError('The second dimension of multipole data arrays' - ' must have a length of 3, 4 or 5') + if self.formalism == 'RM': + if data.shape[1] not in (3, 4): + raise ValueError('For the Reich-Moore formalism, ' + 'data.shape[1] must be 3 or 4. One value for the pole.' + ' One each for the total and absorption residues. ' + 'Possibly one more for a fission residue.') + else: + # Assume self.formalism == 'MLBW' + if data.shape[1] not in (4, 5): + raise ValueError('For the Multi-level Breit-Wigner ' + 'formalism, data.shape[1] must be 4 or 5. One value ' + 'for the pole. One each for the total, competitive, ' + 'and absorption residues. Possibly one mor efor a ' + 'fission residue.') if not np.issubdtype(data.dtype, complex): raise TypeError('Multipole data arrays must be complex dtype') self._data = data @@ -363,6 +357,12 @@ class WindowedMultipole(EqualityMixin): if not np.issubdtype(l_value.dtype, int): raise TypeError('Multipole l_value arrays must be integer' ' dtype') + + self._num_l = len(np.unique(l_value)) + + else: + self._num_l = None + self._l_value = l_value @w_start.setter @@ -442,20 +442,12 @@ class WindowedMultipole(EqualityMixin): 'Python API expects version ' + WMP_VERSION) group = h5file['nuclide'] - out = cls() - # Read scalar values. Note that group['max_w'] is ignored. - length = group['length'].value - windows = group['windows'].value - out.num_l = group['num_l'].value - out.fit_order = group['fit_order'].value - out.fissionable = bool(group['fissionable'].value) - if group['formalism'].value == _FORM_MLBW: - out.formalism = 'MLBW' + out = cls('MLBW') elif group['formalism'].value == _FORM_RM: - out.formalism = 'RM' + out = cls('RM') else: raise ValueError('Unrecognized/Unsupported R-matrix formalism') @@ -466,37 +458,36 @@ class WindowedMultipole(EqualityMixin): # Read arrays. - err = "WMP '{}' array shape is not consistent with the '{}' value" + err = "WMP '{}' array shape is not consistent with the '{}' array shape" out.data = group['data'].value - if out.data.shape[0] != length: - raise ValueError(err.format('data', 'length')) + + out.l_value = group['l_value'].value + if out.l_value.shape[0] != out.data.shape[0]: + raise ValueError(err.format('l_value', 'data')) out.pseudo_k0RS = group['pseudo_K0RS'].value if out.pseudo_k0RS.shape[0] != out.num_l: - raise ValueError(err.format('pseudo_k0RS', 'num_l')) - - out.l_value = group['l_value'].value - if out.l_value.shape[0] != length: - raise ValueError(err.format('l_value', 'length')) + raise ValueError(err.format('pseudo_k0RS', 'l_value')) out.w_start = group['w_start'].value - if out.w_start.shape[0] != windows: - raise ValueError(err.format('w_start', 'windows')) out.w_end = group['w_end'].value - if out.w_end.shape[0] != windows: - raise ValueError(err.format('w_end', 'windows')) + if out.w_end.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('w_end', 'w_start')) out.broaden_poly = group['broaden_poly'].value.astype(np.bool) - if out.broaden_poly.shape[0] != windows: - raise ValueError(err.format('broaden_poly', 'windows')) + if out.broaden_poly.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('broaden_poly', 'w_start')) out.curvefit = group['curvefit'].value - if out.curvefit.shape[0] != windows: - raise ValueError(err.format('curvefit', 'windows')) - if out.curvefit.shape[1] != out.fit_order + 1: - raise ValueError(err.format('curvefit', 'fit_order')) + if out.curvefit.shape[0] != out.w_start.shape[0]: + raise ValueError(err.format('curvefit', 'w_start')) + + # _broaden_wmp_polynomials assumes the curve fit has at least 3 terms. + if out.fit_order < 2: + raise ValueError("Windowed multipole is only supported for " + "curvefits with 3 or more terms.") # Note that all the file 3 data (group['reactions/MT...']) are ignored. From f2c2b4aac8c4591fa48c2f92828436b3ec836ec2 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 17:19:55 -0400 Subject: [PATCH 183/212] Update WMP format docs --- docs/source/io_formats/data_wmp.rst | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/docs/source/io_formats/data_wmp.rst b/docs/source/io_formats/data_wmp.rst index d645c6e8f1..4fa25ee3b6 100644 --- a/docs/source/io_formats/data_wmp.rst +++ b/docs/source/io_formats/data_wmp.rst @@ -30,10 +30,6 @@ Windowed Multipole Library Format Highest energy the windowed multipole part of the library is valid for. - **energy_points** (*double[]*) Energy grid for the pointwise library in the reaction group. - - **fissionable** (*int*) - 1 if this nuclide has fission data. 0 if it does not. - - **fit_order** (*int*) - The order of the curve fit. - **formalism** (*int*) The formalism of the underlying data. Uses the `ENDF-6`_ format formalism numbers. @@ -51,18 +47,12 @@ Windowed Multipole Library Format - **l_value** (*int[]*) The index for a corresponding pole. Equivalent to the :math:`l` quantum number of the resonance the pole comes from :math:`+1`. - - **length** (*int*) - Total count of poles in `data`. - **max_w** (*int*) Maximum number of poles in a window. - **MT_count** (*int*) Number of pointwise tables in the library. - **MT_list** (*int[]*) A list of available MT identifiers. See `ENDF-6`_ for meaning. - - **n_grid** (*int*) - Total length of the pointwise data. - - **num_l** (*int*) - Number of possible :math:`l` quantum states for this nuclide. - **pseudo_K0RS** (*double[]*) :math:`l` dependent value of @@ -90,13 +80,6 @@ Windowed Multipole Library Format The pole to start from for each window. - **w_end** (*int[]*) The pole to end at for each window. - - **windows** (*int*) - Number of windows. - -**/nuclide/reactions/MT** - - **MT_sigma** (*double[]*) -- Cross section value for this reaction. - - **Q_value** (*double*) -- Energy released in this reaction, in eV. - - **threshold** (*int*) -- The first non-zero entry in ``MT_sigma``. .. _h5py: http://docs.h5py.org/en/latest/ .. _ENDF-6: https://www.oecd-nea.org/dbdata/data/manual-endf/endf102.pdf From f047e79540b08aeaa0bca0b72db8ac7529a63685 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 20:48:47 -0400 Subject: [PATCH 184/212] Infer WMP array sizes in F90 --- CMakeLists.txt | 1 - src/input_xml.F90 | 3 +- src/multipole.F90 | 89 ------------------- src/multipole_header.F90 | 179 ++++++++++++++++++++++++++------------- 4 files changed, 120 insertions(+), 152 deletions(-) delete mode 100644 src/multipole.F90 diff --git a/CMakeLists.txt b/CMakeLists.txt index d3673df26c..be62dcd57b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -368,7 +368,6 @@ set(LIBOPENMC_FORTRAN_SRC src/message_passing.F90 src/mgxs_data.F90 src/mgxs_header.F90 - src/multipole.F90 src/multipole_header.F90 src/nuclide_header.F90 src/output.F90 diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 8c3669b2e0..918d471d3c 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -21,7 +21,6 @@ module input_xml use message_passing use mgxs_data, only: create_macro_xs, read_mgxs use mgxs_header - use multipole, only: multipole_read use nuclide_header use output, only: title, header, print_plot use plot_header @@ -4377,7 +4376,7 @@ contains allocate(nuc % multipole) ! Call the read routine - call multipole_read(filename, nuc % multipole, i_table) + call nuc % multipole % from_hdf5(filename) nuc % mp_present = .true. end associate diff --git a/src/multipole.F90 b/src/multipole.F90 deleted file mode 100644 index 0282adb7d9..0000000000 --- a/src/multipole.F90 +++ /dev/null @@ -1,89 +0,0 @@ -module multipole - - use hdf5 - - use constants - use error, only: fatal_error - use hdf5_interface - use multipole_header, only: MultipoleArray, FIT_T, FIT_A, FIT_F, & - MP_FISS, FORM_MLBW, FORM_RM - use nuclide_header, only: nuclides - - implicit none - -contains - -!=============================================================================== -! MULTIPOLE_READ Reads in a multipole HDF5 file with the original API -! specification. Subject to change as the library format matures. -!=============================================================================== - - subroutine multipole_read(filename, multipole, i_table) - character(len=*), intent(in) :: filename ! Filename of the - ! multipole library - ! to load - type(MultipoleArray), intent(out), target :: multipole ! The object to fill - integer, intent(in) :: i_table ! index in nuclides/ - ! sab_tables - - integer(HID_T) :: file_id - integer(HID_T) :: group_id - - ! Intermediate loading components - integer :: is_fissionable - character(len=10) :: version - - associate (nuc => nuclides(i_table)) - - ! Open file for reading and move into the /isotope group - file_id = file_open(filename, 'r', parallel=.true.) - group_id = open_group(file_id, "/nuclide") - - ! Check the file version number. - call read_dataset(version, file_id, "version") - if (version /= VERSION_MULTIPOLE) call fatal_error("The current multipole& - & format version is " // trim(VERSION_MULTIPOLE) // " but the file "& - // trim(filename) // " uses version " // trim(version) // ".") - - ! Load in all the array size scalars - call read_dataset(multipole % length, group_id, "length") - call read_dataset(multipole % windows, group_id, "windows") - call read_dataset(multipole % num_l, group_id, "num_l") - call read_dataset(multipole % fit_order, group_id, "fit_order") - call read_dataset(multipole % max_w, group_id, "max_w") - call read_dataset(is_fissionable, group_id, "fissionable") - if (is_fissionable == MP_FISS) then - multipole % fissionable = .true. - else - multipole % fissionable = .false. - end if - call read_dataset(multipole % formalism, group_id, "formalism") - - call read_dataset(multipole % spacing, group_id, "spacing") - call read_dataset(multipole % sqrtAWR, group_id, "sqrtAWR") - call read_dataset(multipole % start_E, group_id, "start_E") - call read_dataset(multipole % end_E, group_id, "end_E") - - ! Allocate the multipole array components - call multipole % allocate() - - ! Read in arrays - call read_dataset(multipole % data, group_id, "data") - call read_dataset(multipole % pseudo_k0RS, group_id, "pseudo_K0RS") - call read_dataset(multipole % l_value, group_id, "l_value") - call read_dataset(multipole % w_start, group_id, "w_start") - call read_dataset(multipole % w_end, group_id, "w_end") - call read_dataset(multipole % broaden_poly, group_id, "broaden_poly") - - call read_dataset(multipole % curvefit, group_id, "curvefit") - - call close_group(group_id) - - ! Close file - call file_close(file_id) - - end associate - - end subroutine multipole_read - -end module multipole diff --git a/src/multipole_header.F90 b/src/multipole_header.F90 index 143047b0b5..ec82b16a4e 100644 --- a/src/multipole_header.F90 +++ b/src/multipole_header.F90 @@ -1,5 +1,12 @@ module multipole_header + use hdf5 + + use constants + use dict_header, only: DictIntInt + use error, only: fatal_error + use hdf5_interface + implicit none !======================================================================== @@ -29,9 +36,6 @@ module multipole_header FIT_A = 2, & ! Absorption FIT_F = 3 ! Fission - ! Value of 'true' when checking if nuclide is fissionable - integer, parameter :: MP_FISS = 1 - !=============================================================================== ! MULTIPOLE contains all the components needed for the windowed multipole ! temperature dependent cross section libraries for the resolved resonance @@ -42,87 +46,142 @@ module multipole_header !========================================================================= ! Isotope Properties - logical :: fissionable = .false. ! Is this isotope fissionable? - integer :: length ! Number of poles - integer, allocatable :: l_value(:) ! The l index of the pole - real(8), allocatable :: pseudo_k0RS(:) ! The value (sqrt(2*mass neutron)/reduced planck constant) - ! * AWR/(AWR + 1) * scattering radius for each l - complex(8), allocatable :: data(:,:) ! Contains all of the pole-residue data - real(8) :: sqrtAWR ! Square root of the atomic weight ratio + + logical :: fissionable ! Is this isotope fissionable? + integer, allocatable :: l_value(:) ! The l index of the pole + integer :: num_l ! Number of unique l values + real(8), allocatable :: pseudo_k0RS(:) ! The value (sqrt(2*mass neutron + ! /reduced planck constant) + ! * AWR/(AWR + 1) + ! * scattering radius for + ! each l + complex(8), allocatable :: data(:,:) ! Poles and residues + real(8) :: sqrtAWR ! Square root of the atomic + ! weight ratio + integer :: formalism ! R-matrix formalism !========================================================================= ! Windows - integer :: windows ! Number of windows - integer :: fit_order ! Order of the fit. 1 linear, 2 quadratic, etc. + integer :: fit_order ! Order of the fit. 1 linear, + ! 2 quadratic, etc. real(8) :: start_E ! Start energy for the windows real(8) :: end_E ! End energy for the windows - real(8) :: spacing ! The actual spacing in sqrt(E) space. - ! spacing = sqrt(multipole_w%endE - multipole_w%startE)/multipole_w%windows - integer, allocatable :: w_start(:) ! Contains the index of the pole at the start of the window - integer, allocatable :: w_end(:) ! Contains the index of the pole at the end of the window - real(8), allocatable :: curvefit(:,:,:) ! Contains the fitting function. (reaction type, coeff index, window index) + real(8) :: spacing ! The actual spacing in sqrt(E) + ! space. + ! spacing = sqrt(multipole_w % endE - multipole_w % startE) + ! / multipole_w % windows + integer, allocatable :: w_start(:) ! Contains the index of the pole at + ! the start of the window + integer, allocatable :: w_end(:) ! Contains the index of the pole at + ! the end of the window + real(8), allocatable :: curvefit(:,:,:) ! Contains the fitting function. + ! (reaction type, coeff index, + ! window index) integer, allocatable :: broaden_poly(:) ! if 1, broaden, if 0, don't. - !========================================================================= - ! Storage Helpers - integer :: num_l - integer :: max_w + contains - integer :: formalism + procedure :: from_hdf5 => multipole_from_hdf5 - contains - procedure :: allocate => multipole_allocate ! Allocates Multipole end type MultipoleArray contains !=============================================================================== -! MULTIPOLE_ALLOCATE allocates necessary data for Multipole. +! FROM_HDF5 loads multipole data from an HDF5 file. !=============================================================================== - subroutine multipole_allocate(multipole) - class(MultipoleArray), intent(inout) :: multipole ! Multipole object to allocate. + subroutine multipole_from_hdf5(this, filename) + class(MultipoleArray), intent(inout) :: this + character(len=*), intent(in) :: filename - ! This function assumes length, numL, fissionable, windows, fitorder, - ! and formalism are known + character(len=10) :: version + integer :: i, n_poles, n_residue_types, n_windows + integer(HSIZE_T) :: dims_1d(1), dims_2d(2), dims_3d(3) + integer(HID_T) :: file_id + integer(HID_T) :: group_id + integer(HID_T) :: dset + type(DictIntInt) :: l_val_dict - ! Allocate the pole-residue storage. - ! MLBW has one more pole than Reich-Moore, and fissionable nuclides - ! have further one more. - if (multipole % formalism == FORM_MLBW) then - if (multipole % fissionable) then - allocate(multipole % data(5, multipole % length)) - else - allocate(multipole % data(4, multipole % length)) - end if - else if (multipole % formalism == FORM_RM) then - if (multipole % fissionable) then - allocate(multipole % data(4, multipole % length)) - else - allocate(multipole % data(3, multipole % length)) - end if + ! Open file for reading and move into the /isotope group + file_id = file_open(filename, 'r', parallel=.true.) + group_id = open_group(file_id, "/nuclide") + + ! Check the file version number. + call read_dataset(version, file_id, "version") + if (version /= VERSION_MULTIPOLE) call fatal_error("The current multipole& + & format version is " // trim(VERSION_MULTIPOLE) // " but the file "& + // trim(filename) // " uses version " // trim(version) // ".") + + ! Read scalar values. + call read_dataset(this % formalism, group_id, "formalism") + call read_dataset(this % spacing, group_id, "spacing") + call read_dataset(this % sqrtAWR, group_id, "sqrtAWR") + call read_dataset(this % start_E, group_id, "start_E") + call read_dataset(this % end_E, group_id, "end_E") + + ! Read the "data" array. Use its shape to figure out the number of poles + ! and residue types in this data. + dset = open_dataset(group_id, "data") + call get_shape(dset, dims_2d) + n_residue_types = int(dims_2d(1), 4) - 1 + n_poles = int(dims_2d(2), 4) + allocate(this % data(n_residue_types+1, n_poles)) + call read_dataset(this % data, dset) + call close_dataset(dset) + + ! Check to see if this data includes fission residues. + if (this % formalism == FORM_RM) then + this % fissionable = (n_residue_types == 3) + else + ! Assume FORM_MLBW. + this % fissionable = (n_residue_types == 4) + end if + + ! Read the "l_value" array. + allocate(this % l_value(n_poles)) + call read_dataset(this % l_value, group_id, "l_value") + + ! Figure out the number of unique l values in the l_value array. + do i = 1, n_poles + if (.not. l_val_dict % has(this % l_value(i))) then + call l_val_dict % set(i, 0) end if + end do + this % num_l = l_val_dict % size() + call l_val_dict % clear() - ! Allocate the l value table for each pole-residue set. - allocate(multipole % l_value(multipole % length)) + ! Read the "pseudo_K0RS" array. + allocate(this % pseudo_k0RS(this % num_l)) + call read_dataset(this % pseudo_k0RS, group_id, "pseudo_K0RS") - ! Allocate the table of pseudo_k0RS values at each l. - allocate(multipole % pseudo_k0RS(multipole % num_l)) + ! Read the "w_start" array and use its shape to figure out the number of + ! windows. + dset = open_dataset(group_id, "w_start") + call get_shape(dset, dims_1d) + n_windows = int(dims_1d(1), 4) + allocate(this % w_start(n_windows)) + call read_dataset(this % w_start, dset) + call close_dataset(dset) - ! Allocate window start, window end - allocate(multipole % w_start(multipole % windows)) - allocate(multipole % w_end(multipole % windows)) + ! Read the "w_end" and "broaden_poly" arrays. + allocate(this % w_end(n_windows)) + call read_dataset(this % w_end, group_id, "w_end") + allocate(this % broaden_poly(n_windows)) + call read_dataset(this % broaden_poly, group_id, "broaden_poly") - ! Allocate broaden_poly - allocate(multipole % broaden_poly(multipole % windows)) + ! Read the "curvefit" array. + dset = open_dataset(group_id, "curvefit") + call get_shape(dset, dims_3d) + allocate(this % curvefit(dims_3d(1), dims_3d(2), dims_3d(3))) + call read_dataset(this % curvefit, dset) + call close_dataset(dset) + this % fit_order = int(dims_3d(2), 4) - 1 - ! Allocate curvefit - if(multipole % fissionable) then - allocate(multipole % curvefit(FIT_F, multipole % fit_order+1, multipole % windows)) - else - allocate(multipole % curvefit(FIT_A, multipole % fit_order+1, multipole % windows)) - end if - end subroutine + ! Close the group and file. + call close_group(group_id) + call file_close(file_id) + end subroutine multipole_from_hdf5 end module multipole_header From ba15959728ed996e1fd11f6b6f7c7fd4d87af539 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 21:21:12 -0400 Subject: [PATCH 185/212] Add WMP writing functionality to PyAPI --- openmc/data/multipole.py | 52 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/openmc/data/multipole.py b/openmc/data/multipole.py index fd5bf28b3b..ac1e93447d 100644 --- a/openmc/data/multipole.py +++ b/openmc/data/multipole.py @@ -332,7 +332,7 @@ class WindowedMultipole(EqualityMixin): raise ValueError('For the Multi-level Breit-Wigner ' 'formalism, data.shape[1] must be 4 or 5. One value ' 'for the pole. One each for the total, competitive, ' - 'and absorption residues. Possibly one mor efor a ' + 'and absorption residues. Possibly one more for a ' 'fission residue.') if not np.issubdtype(data.dtype, complex): raise TypeError('Multipole data arrays must be complex dtype') @@ -428,6 +428,7 @@ class WindowedMultipole(EqualityMixin): format. """ + if isinstance(group_or_filename, h5py.Group): group = group_or_filename else: @@ -442,7 +443,7 @@ class WindowedMultipole(EqualityMixin): 'Python API expects version ' + WMP_VERSION) group = h5file['nuclide'] - # Read scalar values. Note that group['max_w'] is ignored. + # Read scalars. if group['formalism'].value == _FORM_MLBW: out = cls('MLBW') @@ -489,8 +490,6 @@ class WindowedMultipole(EqualityMixin): raise ValueError("Windowed multipole is only supported for " "curvefits with 3 or more terms.") - # Note that all the file 3 data (group['reactions/MT...']) are ignored. - return out def _evaluate(self, E, T): @@ -652,3 +651,48 @@ class WindowedMultipole(EqualityMixin): fun = np.vectorize(lambda x: self._evaluate(x, T)) return fun(E) + + def to_hdf5(self, path, libver='earliest'): + """Export windowed multipole data to an HDF5 file. + + Parameters + ---------- + path : str + Path to write HDF5 file to + libver : {'earliest', 'latest'} + Compatibility mode for the HDF5 file. 'latest' will produce files + that are less backwards compatible but have performance benefits. + + """ + + # Open file and write version. + f = h5py.File(path, 'w', libver=libver) + f.create_dataset('version', (1, ), dtype='S10') + f['version'][:] = WMP_VERSION.encode('ASCII') + + # Make a nuclide group. + g = f.create_group('nuclide') + + # Write scalars. + if self.formalism == 'MLBW': + g.create_dataset('formalism', + data=np.array(_FORM_MLBW, dtype=np.int32)) + else: + # Assume RM. + g.create_dataset('formalism', + data=np.array(_FORM_RM, dtype=np.int32)) + g.create_dataset('spacing', data=np.array(self.spacing)) + g.create_dataset('sqrtAWR', data=np.array(self.sqrtAWR)) + g.create_dataset('start_E', data=np.array(self.start_E)) + g.create_dataset('end_E', data=np.array(self.end_E)) + + # Write arrays. + g.create_dataset('data', data=self.data) + g.create_dataset('l_value', data=self.l_value) + g.create_dataset('pseudo_K0RS', data=self.pseudo_k0RS) + g.create_dataset('w_start', data=self.w_start) + g.create_dataset('w_end', data=self.w_end) + g.create_dataset('broaden_poly', data=self.broaden_poly) + g.create_dataset('curvefit', data=self.curvefit) + + f.close() From d0b59a21be2d2d0e0f598db12214cc14502fa614 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 21:44:54 -0400 Subject: [PATCH 186/212] Remove unused File 3 stuff from wmp format docs --- docs/source/io_formats/data_wmp.rst | 8 -------- 1 file changed, 8 deletions(-) diff --git a/docs/source/io_formats/data_wmp.rst b/docs/source/io_formats/data_wmp.rst index 4fa25ee3b6..6174e85ff7 100644 --- a/docs/source/io_formats/data_wmp.rst +++ b/docs/source/io_formats/data_wmp.rst @@ -28,8 +28,6 @@ Windowed Multipole Library Format ":math:`r`" and ":math:`i`" identifiers, similar to how `h5py`_ does it. - **end_E** (*double*) Highest energy the windowed multipole part of the library is valid for. - - **energy_points** (*double[]*) - Energy grid for the pointwise library in the reaction group. - **formalism** (*int*) The formalism of the underlying data. Uses the `ENDF-6`_ format formalism numbers. @@ -47,12 +45,6 @@ Windowed Multipole Library Format - **l_value** (*int[]*) The index for a corresponding pole. Equivalent to the :math:`l` quantum number of the resonance the pole comes from :math:`+1`. - - **max_w** (*int*) - Maximum number of poles in a window. - - **MT_count** (*int*) - Number of pointwise tables in the library. - - **MT_list** (*int[]*) - A list of available MT identifiers. See `ENDF-6`_ for meaning. - **pseudo_K0RS** (*double[]*) :math:`l` dependent value of From b71ad222d090497aab04a76b684a3c8e4c72cd02 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Tue, 13 Mar 2018 22:05:59 -0400 Subject: [PATCH 187/212] Expand windowed multipole unit test --- tests/unit_tests/test_data_multipole.py | 26 +++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/unit_tests/test_data_multipole.py b/tests/unit_tests/test_data_multipole.py index 4a4a9f0d21..de7c1cc931 100644 --- a/tests/unit_tests/test_data_multipole.py +++ b/tests/unit_tests/test_data_multipole.py @@ -17,6 +17,13 @@ def u235(): return openmc.data.WindowedMultipole.from_hdf5(filename) +@pytest.fixture(scope='module') +def u234(): + directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] + filename = os.path.join(directory, '092234.h5') + return openmc.data.WindowedMultipole.from_hdf5(filename) + + @pytest.fixture(scope='module') def fe56(): directory = os.environ['OPENMC_MULTIPOLE_LIBRARY'] @@ -24,8 +31,8 @@ def fe56(): return openmc.data.WindowedMultipole.from_hdf5(filename) -def test_evaluate(u235): - """Make sure multipole object can be called.""" +def test_evaluate_rm(u235): + """Make sure a Reich-Moore multipole object can be called.""" energies = [1e-3, 1.0, 10.0, 50.] total, absorption, fission = u235(energies, 0.0) assert total[1] == pytest.approx(90.64895383) @@ -33,6 +40,15 @@ def test_evaluate(u235): assert total[1] == pytest.approx(91.12534964) +def test_evaluate_mlbw(u234): + """Make sure a Multi-Level Breit-Wigner multipole object can be called.""" + energies = [1e-3, 1.0, 10.0, 50.] + total, absorption, fission = u234(energies, 0.0) + assert total[3] == pytest.approx(15.02827953) + total, absorption, fission = u234(energies, 300.0) + assert total[3] == pytest.approx(15.08269143) + + def test_high_l(fe56): """Test a nuclide (Fe56) with a high l-value (4).""" energies = [1e-3, 1.0, 10.0, 1e3, 1e5] @@ -40,3 +56,9 @@ def test_high_l(fe56): assert total[0] == pytest.approx(25.072619556789267) total, absorption, fission = fe56(energies, 300.0) assert total[0] == pytest.approx(27.85535792368082) + + +def test_to_hdf5(tmpdir, u235): + filename = str(tmpdir.join('092235.h5')) + u235.to_hdf5(filename) + assert os.path.exists(filename) From 1e49f3c889c379b667a9f23db1d64f5b2c1be17d Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Wed, 14 Mar 2018 12:51:19 -0400 Subject: [PATCH 188/212] Fix multipole l value counting --- src/multipole_header.F90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/multipole_header.F90 b/src/multipole_header.F90 index ec82b16a4e..7fb438bce1 100644 --- a/src/multipole_header.F90 +++ b/src/multipole_header.F90 @@ -147,7 +147,7 @@ contains ! Figure out the number of unique l values in the l_value array. do i = 1, n_poles if (.not. l_val_dict % has(this % l_value(i))) then - call l_val_dict % set(i, 0) + call l_val_dict % set(this % l_value(i), 0) end if end do this % num_l = l_val_dict % size() From 0508274a3dd97029b914c9031df5e9ff753f042b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 10:36:08 -0600 Subject: [PATCH 189/212] Add useful warnings for add_nuclide/add_element --- docs/source/usersguide/materials.rst | 14 ++++++-- openmc/data/ace.py | 4 +-- openmc/data/data.py | 5 +-- openmc/data/endf.py | 4 +-- openmc/material.py | 49 ++++++++++------------------ tests/unit_tests/test_material.py | 4 +-- 6 files changed, 38 insertions(+), 42 deletions(-) diff --git a/docs/source/usersguide/materials.rst b/docs/source/usersguide/materials.rst index b1e0c151f2..8472768489 100644 --- a/docs/source/usersguide/materials.rst +++ b/docs/source/usersguide/materials.rst @@ -43,14 +43,22 @@ of an element, you specify the element itself. For example, Internally, OpenMC stores data on the atomic masses and natural abundances of all known isotopes and then uses this data to determine what isotopes should be added to the material. When the material is later exported to XML for use by the -:ref:`scripts_openmc` executable, you'll see that any natural elements are +:ref:`scripts_openmc` executable, you'll see that any natural elements were expanded to the naturally-occurring isotopes. +The :meth:`Material.add_element` method can also be used to add uranium at a +specified enrichment through the `enrichment` argument. For example, the +following would add 3.2% enriched uranium to a material:: + + mat.add_element('U', 1.0, enrichment=3.2) + +In addition to U235 and U238, concentrations of U234 and U236 will be present +and are determined through a correlation based on measured data. + Often, cross section libraries don't actually have all naturally-occurring isotopes for a given element. For example, in ENDF/B-VII.1, cross section evaluations are given for O16 and O17 but not for O18. If OpenMC is aware of -what cross sections you will be using (either through the -:attr:`Materials.cross_sections` attribute or the +what cross sections you will be using (through the :envvar:`OPENMC_CROSS_SECTIONS` environment variable), it will attempt to only put isotopes in your model for which you have cross section data. In the case of oxygen in ENDF/B-VII.1, the abundance of O18 would end up being lumped with O16. diff --git a/openmc/data/ace.py b/openmc/data/ace.py index 385408bd48..fa2705220b 100644 --- a/openmc/data/ace.py +++ b/openmc/data/ace.py @@ -22,7 +22,7 @@ import sys import numpy as np from openmc.mixin import EqualityMixin -from openmc.data.endf import ENDF_FLOAT_RE +from openmc.data.endf import _ENDF_FLOAT_RE def ascii_to_binary(ascii_file, binary_file): """Convert an ACE file in ASCII format (type 1) to binary format (type 2). @@ -349,7 +349,7 @@ class Library(EqualityMixin): # after it). If it's too short, then we apply the ENDF float regular # expression. We don't do this by default because it's expensive! if xss.size != nxs[1] + 1: - datastr = ENDF_FLOAT_RE.sub(r'\1e\2', datastr) + datastr = _ENDF_FLOAT_RE.sub(r'\1e\2', datastr) xss = np.fromstring(datastr, sep=' ') assert xss.size == nxs[1] + 1 diff --git a/openmc/data/data.py b/openmc/data/data.py index fd13299617..3a625b6229 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -136,6 +136,8 @@ ATOMIC_NUMBER = {value: key for key, value in ATOMIC_SYMBOL.items()} _ATOMIC_MASS = {} +_GND_NAME_RE = re.compile(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)') + def atomic_mass(isotope): """Return atomic mass of isotope in atomic mass units. @@ -352,8 +354,7 @@ def zam(name): """ try: - symbol, A, state = re.match(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)', - name).groups() + symbol, A, state = _GND_NAME_RE.match(name).groups() except AttributeError: raise ValueError("'{}' does not appear to be a nuclide name in GND " "format.".format(name)) diff --git a/openmc/data/endf.py b/openmc/data/endf.py index c44c66be0c..0d1f402c2f 100644 --- a/openmc/data/endf.py +++ b/openmc/data/endf.py @@ -45,7 +45,7 @@ SUM_RULES = {1: [2, 3], 106: list(range(750, 800)), 107: list(range(800, 850))} -ENDF_FLOAT_RE = re.compile(r'([\s\-\+]?\d*\.\d+)([\+\-]\d+)') +_ENDF_FLOAT_RE = re.compile(r'([\s\-\+]?\d*\.\d+)([\+\-]\d+)') def float_endf(s): @@ -68,7 +68,7 @@ def float_endf(s): The number """ - return float(ENDF_FLOAT_RE.sub(r'\1e\2', s)) + return float(_ENDF_FLOAT_RE.sub(r'\1e\2', s)) def get_text_record(file_obj): diff --git a/openmc/material.py b/openmc/material.py index d52d8a27b4..053e516fae 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -379,33 +379,27 @@ class Material(IDManagerMixin): Parameters ---------- nuclide : str - Nuclide to add + Nuclide to add, e.g., 'Mo95' percent : float Atom or weight percent percent_type : {'ao', 'wo'} 'ao' for atom percent and 'wo' for weight percent """ + cv.check_type('nuclide', nuclide, str) + cv.check_type('percent', percent, Real) + cv.check_value('percent type', percent_type, {'ao', 'wo'}) if self._macroscopic is not None: msg = 'Unable to add a Nuclide to Material ID="{}" as a ' \ 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(nuclide, str): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'non-string value "{}"'.format(self._id, nuclide) - raise ValueError(msg) - - elif not isinstance(percent, Real): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'non-floating point value "{}"'.format(self._id, percent) - raise ValueError(msg) - - elif percent_type not in ('ao', 'wo'): - msg = 'Unable to add a Nuclide to Material ID="{}" with a ' \ - 'percent type "{}"'.format(self._id, percent_type) - raise ValueError(msg) + # If nuclide name doesn't look valid, give a warning + try: + openmc.data.zam(nuclide) + except ValueError as e: + warnings.warn(str(e)) self._nuclides.append((nuclide, percent, percent_type)) @@ -493,7 +487,7 @@ class Material(IDManagerMixin): Parameters ---------- element : str - Element to add + Element to add, e.g., 'Zr' percent : float Atom or weight percent percent_type : {'ao', 'wo'}, optional @@ -505,27 +499,15 @@ class Material(IDManagerMixin): (natural composition). """ + cv.check_type('nuclide', element, str) + cv.check_type('percent', percent, Real) + cv.check_value('percent type', percent_type, {'ao', 'wo'}) if self._macroscopic is not None: msg = 'Unable to add an Element to Material ID="{}" as a ' \ 'macroscopic data-set has already been added'.format(self._id) raise ValueError(msg) - if not isinstance(element, str): - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'non-string value "{}"'.format(self._id, element) - raise ValueError(msg) - - if not isinstance(percent, Real): - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'non-floating point value "{}"'.format(self._id, percent) - raise ValueError(msg) - - if percent_type not in ['ao', 'wo']: - msg = 'Unable to add an Element to Material ID="{}" with a ' \ - 'percent type "{}"'.format(self._id, percent_type) - raise ValueError(msg) - if enrichment is not None: if not isinstance(enrichment, Real): msg = 'Unable to add an Element to Material ID="{}" with a ' \ @@ -551,6 +533,11 @@ class Material(IDManagerMixin): format(enrichment, self._id) warnings.warn(msg) + # Make sure element name is just that + if not element.isalpha(): + raise ValueError("Element name should be given by the " + "element's symbol, e.g., 'Zr'") + # Add naturally-occuring isotopes element = openmc.Element(element) for nuclide in element.expand(percent, percent_type, enrichment): diff --git a/tests/unit_tests/test_material.py b/tests/unit_tests/test_material.py index c251df3a6d..b7b745408d 100644 --- a/tests/unit_tests/test_material.py +++ b/tests/unit_tests/test_material.py @@ -15,9 +15,9 @@ def test_nuclides(uo2): """Test adding/removing nuclides.""" m = openmc.Material() m.add_nuclide('U235', 1.0) - with pytest.raises(ValueError): + with pytest.raises(TypeError): m.add_nuclide('H1', '1.0') - with pytest.raises(ValueError): + with pytest.raises(TypeError): m.add_nuclide(1.0, 'H1') with pytest.raises(ValueError): m.add_nuclide('H1', 1.0, 'oa') From f415700c86d5e4bbb8498b216c95e5fa5a78e00c Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 10:57:02 -0600 Subject: [PATCH 190/212] Make materials with actinides depletable by default --- openmc/material.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/openmc/material.py b/openmc/material.py index 053e516fae..88479d8df6 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -88,7 +88,7 @@ class Material(IDManagerMixin): self.name = name self.temperature = temperature self._density = None - self._density_units = '' + self._density_units = 'sum' self._depletable = False self._paths = None self._num_instances = None @@ -397,9 +397,13 @@ class Material(IDManagerMixin): # If nuclide name doesn't look valid, give a warning try: - openmc.data.zam(nuclide) + Z, _, _ = openmc.data.zam(nuclide) except ValueError as e: warnings.warn(str(e)) + else: + # For actinides, have the material be depletable by default + if Z >= 89: + self.depletable = True self._nuclides.append((nuclide, percent, percent_type)) @@ -541,7 +545,7 @@ class Material(IDManagerMixin): # Add naturally-occuring isotopes element = openmc.Element(element) for nuclide in element.expand(percent, percent_type, enrichment): - self._nuclides.append(nuclide) + self.add_nuclide(*nuclide) def add_s_alpha_beta(self, name, fraction=1.0): r"""Add an :math:`S(\alpha,\beta)` table to the material From ed7edf414179f34ccb9247f847b931e507c3ec21 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 12:09:27 -0600 Subject: [PATCH 191/212] Have Universe.plot return AxesImage. Add Plot.to_image method --- openmc/plots.py | 37 +++++++++++++++++++++++++++++++++++++ openmc/plotter.py | 3 ++- openmc/universe.py | 27 ++++++++++++++------------- 3 files changed, 53 insertions(+), 14 deletions(-) diff --git a/openmc/plots.py b/openmc/plots.py index 4414a39e13..a948c2a48e 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -1,6 +1,7 @@ from collections.abc import Iterable, Mapping from numbers import Real, Integral from xml.etree import ElementTree as ET +import subprocess import sys import warnings @@ -650,6 +651,42 @@ class Plot(IDManagerMixin): return element + def to_image(self, openmc_exec='openmc', cwd='.', convert_exec='convert'): + """Render plot as an image + + Parameters + ---------- + openmc_exec : str + Path to OpenMC executable + cwd : str, optional + Path to working directory to run in + convert_exec : str, optional + Command that can convert PPM files into PNG files + + Returns + ------- + IPython.display.Image + Image generated + + """ + from IPython.display import Image + + # Create plots.xml + Plots([self]).export_to_xml() + + # Run OpenMC in geometry plotting mode + openmc.plot_geometry(False, openmc_exec, cwd) + + # Convert to .png + if self.filename is not None: + ppm_file = '{}.ppm'.format(self.filename) + else: + ppm_file = 'plot_{}.ppm'.format(self.id) + png_file = ppm_file.replace('.ppm', '.png') + subprocess.check_call([convert_exec, ppm_file, png_file]) + + return Image(png_file) + class Plots(cv.CheckedList): """Collection of Plots used for an OpenMC simulation. diff --git a/openmc/plotter.py b/openmc/plotter.py index 1bf6fe46fd..191b50c563 100644 --- a/openmc/plotter.py +++ b/openmc/plotter.py @@ -2,7 +2,6 @@ from numbers import Integral, Real from itertools import chain import string -import matplotlib.pyplot as plt import numpy as np import openmc.checkvalue as cv @@ -125,6 +124,8 @@ def plot_xs(this, types, divisor_types=None, temperature=294., data_type=None, generated. """ + import matplotlib.pyplot as plt + cv.check_type("plot_CE", plot_CE, bool) if data_type is None: diff --git a/openmc/universe.py b/openmc/universe.py index 55f574c536..77138adcce 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -4,7 +4,6 @@ from numbers import Integral, Real import random import sys -import matplotlib.pyplot as plt import numpy as np import openmc @@ -184,10 +183,14 @@ class Universe(IDManagerMixin): return [] def plot(self, origin=(0., 0., 0.), width=(1., 1.), pixels=(200, 200), - basis='xy', color_by='cell', colors=None, filename=None, seed=None, + basis='xy', color_by='cell', colors=None, seed=None, **kwargs): """Display a slice plot of the universe. + To display or save the plot, call :func:`matplotlib.pyplot.show` or + :func:`matplotlib.pyplot.savefig`. In a Jupyter notebook, enabling the + matplotlib inline backend will show the plot inline. + Parameters ---------- origin : Iterable of float @@ -212,9 +215,6 @@ class Universe(IDManagerMixin): water = openmc.Cell(fill=h2o) universe.plot(..., colors={water: (0., 0., 1.)) - filename : str or None - Filename to save plot to. If no filename is given, the plot will be - displayed using the currently enabled matplotlib backend. seed : hashable object or None Hashable object which is used to seed the random number generator used to select colors. If None, the generator is seeded from the @@ -223,7 +223,14 @@ class Universe(IDManagerMixin): All keyword arguments are passed to :func:`matplotlib.pyplot.imshow`. + Returns + ------- + matplotlib.image.AxesImage + Resulting image + """ + import matplotlib.pyplot as plt + # Seed the random number generator if seed is not None: random.seed(seed) @@ -298,14 +305,8 @@ class Universe(IDManagerMixin): img[j, i, :] = colors[obj] # Display image - plt.imshow(img, extent=(x_min, x_max, y_min, y_max), - interpolation='nearest', **kwargs) - - # Show or save the plot - if filename is None: - plt.show() - else: - plt.savefig(filename) + return plt.imshow(img, extent=(x_min, x_max, y_min, y_max), + interpolation='nearest', **kwargs) def add_cell(self, cell): """Add a cell to the universe. From 23324fe24b62b0f92e609a4e78c40847277ed3d8 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 16:18:51 -0600 Subject: [PATCH 192/212] Fix broken tests --- tests/regression_tests/asymmetric_lattice/inputs_true.dat | 2 +- .../create_fission_neutrons/inputs_true.dat | 2 +- tests/regression_tests/diff_tally/inputs_true.dat | 2 +- tests/regression_tests/distribmat/inputs_true.dat | 4 ++-- tests/regression_tests/filter_energyfun/inputs_true.dat | 4 ++-- tests/regression_tests/filter_mesh/inputs_true.dat | 2 +- tests/regression_tests/fixed_source/inputs_true.dat | 2 +- tests/regression_tests/iso_in_lab/inputs_true.dat | 2 +- .../mgxs_library_ce_to_mg/inputs_true.dat | 2 +- .../mgxs_library_condense/inputs_true.dat | 2 +- .../mgxs_library_distribcell/inputs_true.dat | 2 +- tests/regression_tests/mgxs_library_hdf5/inputs_true.dat | 2 +- tests/regression_tests/mgxs_library_mesh/inputs_true.dat | 2 +- .../mgxs_library_no_nuclides/inputs_true.dat | 2 +- .../mgxs_library_nuclides/inputs_true.dat | 2 +- tests/regression_tests/multipole/inputs_true.dat | 2 +- tests/regression_tests/periodic/inputs_true.dat | 2 +- .../regression_tests/resonance_scattering/inputs_true.dat | 2 +- tests/regression_tests/salphabeta/inputs_true.dat | 8 ++++---- tests/regression_tests/source/inputs_true.dat | 2 +- tests/regression_tests/surface_tally/inputs_true.dat | 2 +- tests/regression_tests/tallies/inputs_true.dat | 2 +- tests/regression_tests/tally_aggregation/inputs_true.dat | 2 +- tests/regression_tests/tally_arithmetic/inputs_true.dat | 2 +- tests/regression_tests/tally_slice_merge/inputs_true.dat | 2 +- tests/regression_tests/triso/inputs_true.dat | 2 +- tests/regression_tests/volume_calc/inputs_true.dat | 2 +- tests/unit_tests/test_universe.py | 1 - 28 files changed, 32 insertions(+), 33 deletions(-) diff --git a/tests/regression_tests/asymmetric_lattice/inputs_true.dat b/tests/regression_tests/asymmetric_lattice/inputs_true.dat index 672f6bee12..bbdc79715b 100644 --- a/tests/regression_tests/asymmetric_lattice/inputs_true.dat +++ b/tests/regression_tests/asymmetric_lattice/inputs_true.dat @@ -56,7 +56,7 @@ - + diff --git a/tests/regression_tests/create_fission_neutrons/inputs_true.dat b/tests/regression_tests/create_fission_neutrons/inputs_true.dat index 9aeabbb57b..b0ca896476 100644 --- a/tests/regression_tests/create_fission_neutrons/inputs_true.dat +++ b/tests/regression_tests/create_fission_neutrons/inputs_true.dat @@ -10,7 +10,7 @@ - + diff --git a/tests/regression_tests/diff_tally/inputs_true.dat b/tests/regression_tests/diff_tally/inputs_true.dat index ff134bd5c3..909475f962 100644 --- a/tests/regression_tests/diff_tally/inputs_true.dat +++ b/tests/regression_tests/diff_tally/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/distribmat/inputs_true.dat b/tests/regression_tests/distribmat/inputs_true.dat index 85d35b0810..39e611e16a 100644 --- a/tests/regression_tests/distribmat/inputs_true.dat +++ b/tests/regression_tests/distribmat/inputs_true.dat @@ -26,11 +26,11 @@ - + - + diff --git a/tests/regression_tests/filter_energyfun/inputs_true.dat b/tests/regression_tests/filter_energyfun/inputs_true.dat index d857451cb0..418354fc2b 100644 --- a/tests/regression_tests/filter_energyfun/inputs_true.dat +++ b/tests/regression_tests/filter_energyfun/inputs_true.dat @@ -148,7 +148,7 @@ - + @@ -156,7 +156,7 @@ - + diff --git a/tests/regression_tests/filter_mesh/inputs_true.dat b/tests/regression_tests/filter_mesh/inputs_true.dat index 6d14f9e7e3..ca063b7ce9 100644 --- a/tests/regression_tests/filter_mesh/inputs_true.dat +++ b/tests/regression_tests/filter_mesh/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/fixed_source/inputs_true.dat b/tests/regression_tests/fixed_source/inputs_true.dat index 2e0d57b0c1..f1aebb3b2b 100644 --- a/tests/regression_tests/fixed_source/inputs_true.dat +++ b/tests/regression_tests/fixed_source/inputs_true.dat @@ -5,7 +5,7 @@ - + diff --git a/tests/regression_tests/iso_in_lab/inputs_true.dat b/tests/regression_tests/iso_in_lab/inputs_true.dat index 9e30f245f9..2a302ada67 100644 --- a/tests/regression_tests/iso_in_lab/inputs_true.dat +++ b/tests/regression_tests/iso_in_lab/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat b/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat index 8e8cde2818..70996fe378 100644 --- a/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_ce_to_mg/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_condense/inputs_true.dat b/tests/regression_tests/mgxs_library_condense/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/regression_tests/mgxs_library_condense/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_condense/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat b/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat index d7a4a186ac..ba7dc05ff7 100644 --- a/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_distribcell/inputs_true.dat @@ -39,7 +39,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat b/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_hdf5/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_mesh/inputs_true.dat b/tests/regression_tests/mgxs_library_mesh/inputs_true.dat index 4756b27bfb..aa2c904b19 100644 --- a/tests/regression_tests/mgxs_library_mesh/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_mesh/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat index d2f28d0fe0..ef6c4c5206 100644 --- a/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_no_nuclides/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat b/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat index 826eb5b623..b720bfcbba 100644 --- a/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat +++ b/tests/regression_tests/mgxs_library_nuclides/inputs_true.dat @@ -12,7 +12,7 @@ - + diff --git a/tests/regression_tests/multipole/inputs_true.dat b/tests/regression_tests/multipole/inputs_true.dat index 0d1fe99bdc..d1ef3e00aa 100644 --- a/tests/regression_tests/multipole/inputs_true.dat +++ b/tests/regression_tests/multipole/inputs_true.dat @@ -27,7 +27,7 @@ - + diff --git a/tests/regression_tests/periodic/inputs_true.dat b/tests/regression_tests/periodic/inputs_true.dat index 61958701b2..6f613a1602 100644 --- a/tests/regression_tests/periodic/inputs_true.dat +++ b/tests/regression_tests/periodic/inputs_true.dat @@ -18,7 +18,7 @@ - + diff --git a/tests/regression_tests/resonance_scattering/inputs_true.dat b/tests/regression_tests/resonance_scattering/inputs_true.dat index 70fe165fd5..2301ccf762 100644 --- a/tests/regression_tests/resonance_scattering/inputs_true.dat +++ b/tests/regression_tests/resonance_scattering/inputs_true.dat @@ -5,7 +5,7 @@ - + diff --git a/tests/regression_tests/salphabeta/inputs_true.dat b/tests/regression_tests/salphabeta/inputs_true.dat index 02e6813f02..ede96d3769 100644 --- a/tests/regression_tests/salphabeta/inputs_true.dat +++ b/tests/regression_tests/salphabeta/inputs_true.dat @@ -12,19 +12,19 @@ - + - + - + @@ -32,7 +32,7 @@ - + diff --git a/tests/regression_tests/source/inputs_true.dat b/tests/regression_tests/source/inputs_true.dat index da230e0e50..6dd913edc0 100644 --- a/tests/regression_tests/source/inputs_true.dat +++ b/tests/regression_tests/source/inputs_true.dat @@ -5,7 +5,7 @@ - + 294 diff --git a/tests/regression_tests/surface_tally/inputs_true.dat b/tests/regression_tests/surface_tally/inputs_true.dat index e66d44273a..fc10110eee 100644 --- a/tests/regression_tests/surface_tally/inputs_true.dat +++ b/tests/regression_tests/surface_tally/inputs_true.dat @@ -11,7 +11,7 @@ - + diff --git a/tests/regression_tests/tallies/inputs_true.dat b/tests/regression_tests/tallies/inputs_true.dat index a85491e943..2c33a8fa0d 100644 --- a/tests/regression_tests/tallies/inputs_true.dat +++ b/tests/regression_tests/tallies/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/tally_aggregation/inputs_true.dat b/tests/regression_tests/tally_aggregation/inputs_true.dat index 7a8bf46133..86806572a0 100644 --- a/tests/regression_tests/tally_aggregation/inputs_true.dat +++ b/tests/regression_tests/tally_aggregation/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/tally_arithmetic/inputs_true.dat b/tests/regression_tests/tally_arithmetic/inputs_true.dat index 743ca3c582..3605005add 100644 --- a/tests/regression_tests/tally_arithmetic/inputs_true.dat +++ b/tests/regression_tests/tally_arithmetic/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/tally_slice_merge/inputs_true.dat b/tests/regression_tests/tally_slice_merge/inputs_true.dat index b1c089c965..ccd3655f9e 100644 --- a/tests/regression_tests/tally_slice_merge/inputs_true.dat +++ b/tests/regression_tests/tally_slice_merge/inputs_true.dat @@ -148,7 +148,7 @@ - + diff --git a/tests/regression_tests/triso/inputs_true.dat b/tests/regression_tests/triso/inputs_true.dat index fdbc1cb5f1..6d674b4502 100644 --- a/tests/regression_tests/triso/inputs_true.dat +++ b/tests/regression_tests/triso/inputs_true.dat @@ -393,7 +393,7 @@ - + diff --git a/tests/regression_tests/volume_calc/inputs_true.dat b/tests/regression_tests/volume_calc/inputs_true.dat index 28f1cbd9fc..607921af26 100644 --- a/tests/regression_tests/volume_calc/inputs_true.dat +++ b/tests/regression_tests/volume_calc/inputs_true.dat @@ -18,7 +18,7 @@ - + diff --git a/tests/unit_tests/test_universe.py b/tests/unit_tests/test_universe.py index 59e34e2017..89904524b6 100644 --- a/tests/unit_tests/test_universe.py +++ b/tests/unit_tests/test_universe.py @@ -59,7 +59,6 @@ def test_plot(run_in_tmpdir, sphere_model): pixels=(10, 10), color_by='material', colors=colors, - filename='test.png' ) From 8487915f2a66e2875b9970e65f77be45b32982aa Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 2 Mar 2018 16:19:10 -0600 Subject: [PATCH 193/212] Use ufloat for k_combined in statepoint --- openmc/mgxs/library.py | 2 +- openmc/model/model.py | 2 +- openmc/search.py | 4 ++-- openmc/statepoint.py | 17 ++++++++++------- tests/regression_tests/entropy/test.py | 4 ++-- tests/regression_tests/mg_convert/test.py | 4 ++-- tests/testing_harness.py | 2 +- 7 files changed, 19 insertions(+), 16 deletions(-) diff --git a/openmc/mgxs/library.py b/openmc/mgxs/library.py index 9add7004bb..ed8e3f076c 100644 --- a/openmc/mgxs/library.py +++ b/openmc/mgxs/library.py @@ -587,7 +587,7 @@ class Library(object): self._nuclides = statepoint.summary.nuclides if statepoint.run_mode == 'eigenvalue': - self._keff = statepoint.k_combined[0] + self._keff = statepoint.k_combined.n # Load tallies for each MGXS for each domain and mgxs type for domain in self.domains: diff --git a/openmc/model/model.py b/openmc/model/model.py index cd51533217..7a81292c1a 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -210,7 +210,7 @@ class Model(object): Returns ------- - 2-tuple of float + uncertainties.UFloat Combined estimator of k-effective from the statepoint """ diff --git a/openmc/search.py b/openmc/search.py index 75935097e4..6be8a50ea5 100644 --- a/openmc/search.py +++ b/openmc/search.py @@ -60,9 +60,9 @@ def _search_keff(guess, target, model_builder, model_args, print_iterations, if print_iterations: text = 'Iteration: {}; Guess of {:.2e} produced a keff of ' + \ '{:1.5f} +/- {:1.5f}' - print(text.format(len(guesses), guess, keff[0], keff[1])) + print(text.format(len(guesses), guess, keff.n, keff.s)) - return (keff[0] - target) + return keff.n - target def search_for_keff(model_builder, initial_guess=None, target=1.0, diff --git a/openmc/statepoint.py b/openmc/statepoint.py index 4656e08560..eb011d8742 100644 --- a/openmc/statepoint.py +++ b/openmc/statepoint.py @@ -1,3 +1,4 @@ +from datetime import datetime import re import os import warnings @@ -5,6 +6,7 @@ import glob import numpy as np import h5py +from uncertainties import ufloat import openmc import openmc.checkvalue as cv @@ -47,8 +49,8 @@ class StatePoint(object): CMFD fission source distribution over all mesh cells and energy groups. current_batch : int Number of batches simulated - date_and_time : str - Date and time when simulation began + date_and_time : datetime.datetime + Date and time at which statepoint was written entropy : numpy.ndarray Shannon entropy of fission source at each batch filters : dict @@ -59,8 +61,8 @@ class StatePoint(object): global_tallies : numpy.ndarray of compound datatype Global tallies for k-effective estimates and leakage. The compound datatype has fields 'name', 'sum', 'sum_sq', 'mean', and 'std_dev'. - k_combined : list - Combined estimator for k-effective and its uncertainty + k_combined : uncertainties.UFloat + Combined estimator for k-effective k_col_abs : float Cross-product of collision and absorption estimates of k-effective k_col_tra : float @@ -187,7 +189,8 @@ class StatePoint(object): @property def date_and_time(self): - return self._f.attrs['date_and_time'].decode() + s = self._f.attrs['date_and_time'].decode() + return datetime.strptime(s, '%Y-%m-%d %H:%M:%S') @property def entropy(self): @@ -255,7 +258,7 @@ class StatePoint(object): @property def k_combined(self): if self.run_mode == 'eigenvalue': - return self._f['k_combined'].value + return ufloat(*self._f['k_combined'].value) else: return None @@ -457,7 +460,7 @@ class StatePoint(object): @property def version(self): - return tuple(self._f.attrs['version']) + return tuple(self._f.attrs['openmc_version']) @property def summary(self): diff --git a/tests/regression_tests/entropy/test.py b/tests/regression_tests/entropy/test.py index 0f1052b6b8..10a11e3008 100644 --- a/tests/regression_tests/entropy/test.py +++ b/tests/regression_tests/entropy/test.py @@ -14,11 +14,11 @@ class EntropyTestHarness(TestHarness): with StatePoint(statepoint) as sp: # Write out k-combined. outstr = 'k-combined:\n' - outstr += '{0:12.6E} {1:12.6E}\n'.format(*sp.k_combined) + outstr += '{:12.6E} {:12.6E}\n'.format(sp.k_combined.n, sp.k_combined.s) # Write out entropy data. outstr += 'entropy:\n' - results = ['{0:12.6E}'.format(x) for x in sp.entropy] + results = ['{:12.6E}'.format(x) for x in sp.entropy] outstr += '\n'.join(results) + '\n' return outstr diff --git a/tests/regression_tests/mg_convert/test.py b/tests/regression_tests/mg_convert/test.py index 5b816a1cd0..1ace10c80b 100755 --- a/tests/regression_tests/mg_convert/test.py +++ b/tests/regression_tests/mg_convert/test.py @@ -144,8 +144,8 @@ class MGXSTestHarness(PyAPITestHarness): with openmc.StatePoint('statepoint.{}.h5'.format(batches)) as sp: # Write out k-combined. outstr += 'k-combined:\n' - form = '{0:12.6E} {1:12.6E}\n' - outstr += form.format(sp.k_combined[0], sp.k_combined[1]) + form = '{:12.6E} {:12.6E}\n' + outstr += form.format(sp.k_combined.n, sp.k_combined.s) return outstr diff --git a/tests/testing_harness.py b/tests/testing_harness.py index 92d477e238..fb07575ce7 100644 --- a/tests/testing_harness.py +++ b/tests/testing_harness.py @@ -75,7 +75,7 @@ class TestHarness(object): # Write out k-combined. outstr = 'k-combined:\n' form = '{0:12.6E} {1:12.6E}\n' - outstr += form.format(sp.k_combined[0], sp.k_combined[1]) + outstr += form.format(sp.k_combined.n, sp.k_combined.s) # Write out tally data. for i, tally_ind in enumerate(sp.tallies): From ac28407aa2d54b96ff911f69fdb982f2f14728e0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 3 Mar 2018 15:55:12 -0600 Subject: [PATCH 194/212] Don't have atomic_mass/atomic_weight return None for invalid --- openmc/data/data.py | 29 +++++++++++++++-------------- tests/unit_tests/test_data_misc.py | 13 +++++++++++++ 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/openmc/data/data.py b/openmc/data/data.py index 3a625b6229..90d5903e73 100644 --- a/openmc/data/data.py +++ b/openmc/data/data.py @@ -1,10 +1,9 @@ import itertools +from math import sqrt import os import re from warnings import warn -from numpy import sqrt - # Isotopic abundances from Meija J, Coplen T B, et al, "Isotopic compositions # of the elements 2013 (IUPAC Technical Report)", Pure. Appl. Chem. 88 (3), @@ -142,19 +141,18 @@ _GND_NAME_RE = re.compile(r'([A-Zn][a-z]*)(\d+)((?:_[em]\d+)?)') def atomic_mass(isotope): """Return atomic mass of isotope in atomic mass units. - Atomic mass data comes from the Atomic Mass Evaluation 2012, published in - Chinese Physics C 36 (2012), 1287--1602. + Atomic mass data comes from the `Atomic Mass Evaluation 2012 + `_. Parameters ---------- isotope : str - Name of isotope, e.g. 'Pu239' + Name of isotope, e.g., 'Pu239' Returns ------- - float or None - Atomic mass of isotope in atomic mass units. If the isotope listed does - not have a known atomic mass, None is returned. + float + Atomic mass of isotope in [amu] """ if not _ATOMIC_MASS: @@ -185,7 +183,7 @@ def atomic_mass(isotope): if '_' in isotope: isotope = isotope[:isotope.find('_')] - return _ATOMIC_MASS.get(isotope.lower()) + return _ATOMIC_MASS[isotope.lower()] def atomic_weight(element): @@ -201,16 +199,19 @@ def atomic_weight(element): Returns ------- - float or None - Atomic weight of element in atomic mass units. If the element listed does - not exist, None is returned. + float + Atomic weight of element in [amu] """ weight = 0. for nuclide, abundance in NATURAL_ABUNDANCE.items(): if re.match(r'{}\d+'.format(element), nuclide): weight += atomic_mass(nuclide) * abundance - return None if weight == 0. else weight + if weight > 0.: + return weight + else: + raise ValueError("No naturally-occurring isotopes for element '{}'." + .format(element)) def water_density(temperature, pressure=0.1013): @@ -236,7 +237,7 @@ def water_density(temperature, pressure=0.1013): Returns ------- float - Water density in units of [g / cm^3] + Water density in units of [g/cm^3] """ diff --git a/tests/unit_tests/test_data_misc.py b/tests/unit_tests/test_data_misc.py index 04ca0f1031..34686b567f 100644 --- a/tests/unit_tests/test_data_misc.py +++ b/tests/unit_tests/test_data_misc.py @@ -50,6 +50,19 @@ def test_thin(): assert f(1.0) == pytest.approx(np.sin(1.0), 0.001) +def test_atomic_mass(): + assert openmc.data.atomic_mass('H1') == 1.00782503223 + assert openmc.data.atomic_mass('U235') == 235.043930131 + with pytest.raises(KeyError): + openmc.data.atomic_mass('U100') + + +def test_atomic_weight(): + assert openmc.data.atomic_weight('C') == 12.011115164862904 + with pytest.raises(ValueError): + openmc.data.atomic_weight('Qt') + + def test_water_density(): dens = openmc.data.water_density # These test values are from IAPWS R7-97(2012). They are actually specific From 0efd0424204b0568ff6b48875b3618cd954a4dcd Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Sat, 3 Mar 2018 16:27:45 -0600 Subject: [PATCH 195/212] Fix display of version number and copyright year --- src/output.F90 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/output.F90 b/src/output.F90 index 1bf0c46d08..964289126c 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -165,12 +165,12 @@ contains subroutine print_version() if (master) then - write(UNIT=OUTPUT_UNIT, FMT='(1X,A,1X,I1,".",I1,".",I1)') & + write(UNIT=OUTPUT_UNIT, FMT='(1X,A,1X,I1,".",I2,".",I1)') & "OpenMC version", VERSION_MAJOR, VERSION_MINOR, VERSION_RELEASE #ifdef GIT_SHA1 write(UNIT=OUTPUT_UNIT, FMT='(1X,A,A)') "Git SHA1: ", GIT_SHA1 #endif - write(UNIT=OUTPUT_UNIT, FMT=*) "Copyright (c) 2011-2015 & + write(UNIT=OUTPUT_UNIT, FMT=*) "Copyright (c) 2011-2018 & &Massachusetts Institute of Technology" write(UNIT=OUTPUT_UNIT, FMT=*) "MIT/X license at & &" From dca39f87e2730aba4152e7d51849b42916319ab0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 5 Mar 2018 19:56:42 -0600 Subject: [PATCH 196/212] Use gnd_name in _get_metadata --- openmc/data/neutron.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/openmc/data/neutron.py b/openmc/data/neutron.py index 0aa1fe7d83..1cc0e38879 100644 --- a/openmc/data/neutron.py +++ b/openmc/data/neutron.py @@ -15,7 +15,7 @@ import h5py from . import HDF5_VERSION, HDF5_VERSION_MAJOR from .ace import Library, Table, get_table -from .data import ATOMIC_SYMBOL, K_BOLTZMANN, EV_PER_MEV +from .data import ATOMIC_SYMBOL, K_BOLTZMANN, EV_PER_MEV, gnd_name from .endf import Evaluation, SUM_RULES, get_head_record, get_tab1_record from .fission_energy import FissionEnergyRelease from .function import Tabulated1D, Sum, ResonancesWithBackground @@ -93,9 +93,7 @@ def _get_metadata(zaid, metastable_scheme='nndc'): # Determine name element = ATOMIC_SYMBOL[Z] - name = '{}{}'.format(element, mass_number) - if metastable > 0: - name += '_m{}'.format(metastable) + name = gnd_name(Z, mass_number, metastable) return (name, element, Z, mass_number, metastable) From 9904e64910eec94e63c071f1c5d8077be9b756e7 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Wed, 7 Mar 2018 06:31:27 -0600 Subject: [PATCH 197/212] Add three papers to list of publications --- docs/source/publications.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/source/publications.rst b/docs/source/publications.rst index 7578fee6b1..b88bdc0f0c 100644 --- a/docs/source/publications.rst +++ b/docs/source/publications.rst @@ -57,6 +57,11 @@ Benchmarking Coupling and Multi-physics -------------------------- +- Jun Chen, Liangzhi Cao, Chuanqi Zhao, and Zhouyu Liu, "`Development of + Subchannel Code SUBSC for high-fidelity multi-physics coupling application + `_", Energy Procedia, **127**, + 264-274 (2017). + - Tianliang Hu, Liangzhu Cao, Hongchun Wu, Xianan Du, and Mingtao He, "`Coupled neutrons and thermal-hydraulics simulation of molten salt reactors based on OpenMC/TANSY `_," @@ -98,6 +103,11 @@ Coupling and Multi-physics Geometry and Visualization -------------------------- +- Jin-Yang Li, Long Gu, Hu-Shan Xu, Nadezha Korepanova, Rui Yu, Yan-Lei Zhu, and + Chang-Ping Qin, "`CAD modeling study on FLUKA and OpenMC for accelerator + driven system simulation `_", + *Ann. Nucl. Energy*, **114**, 329-341 (2018). + - Logan Abel, William Boyd, Benoit Forget, and Kord Smith, "Interactive Visualization of Multi-Group Cross Sections on High-Fidelity Spatial Meshes," *Trans. Am. Nucl. Soc.*, **114**, 391-394 (2016). @@ -114,6 +124,11 @@ Geometry and Visualization Miscellaneous ------------- +- Bruno Merk, Dzianis Litskevich, R. Gregg, and A. R. Mount, "`Demand driven + salt clean-up in a molten salt fast reactor -- Defining a priority list + `_", *PLOS One*, **13**, + e0192020 (2018). + - Adam G. Nelson, Samuel Shaner, William Boyd, and Paul K. Romano, "Incorporation of a Multigroup Transport Capability in the OpenMC Monte Carlo Particle Transport Code," *Trans. Am. Nucl. Soc.*, **117**, 679-681 (2017). From 9e912a933dcadab2c240d928dd685088548d3193 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Mar 2018 10:41:43 -0500 Subject: [PATCH 198/212] Support energyout filters in C API --- openmc/capi/filter.py | 2 +- src/tallies/tally_filter_energy.F90 | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index 79c19a6248..5a5df4814d 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -128,7 +128,7 @@ class EnergyFilter(Filter): self._index, len(energies), energies_p) -class EnergyoutFilter(Filter): +class EnergyoutFilter(EnergyFilter): filter_type = 'energyout' diff --git a/src/tallies/tally_filter_energy.F90 b/src/tallies/tally_filter_energy.F90 index 2a247cf358..caba6755d1 100644 --- a/src/tallies/tally_filter_energy.F90 +++ b/src/tallies/tally_filter_energy.F90 @@ -211,6 +211,10 @@ contains energies = C_LOC(f % bins) n = size(f % bins) err = 0 + type is (EnergyoutFilter) + energies = C_LOC(f % bins) + n = size(f % bins) + err = 0 class default err = E_INVALID_TYPE call set_errmsg("Tried to get energy bins on a non-energy filter.") @@ -242,6 +246,11 @@ contains if (allocated(f % bins)) deallocate(f % bins) allocate(f % bins(n)) f % bins(:) = energies + type is (EnergyoutFilter) + f % n_bins = n - 1 + if (allocated(f % bins)) deallocate(f % bins) + allocate(f % bins(n)) + f % bins(:) = energies class default err = E_INVALID_TYPE call set_errmsg("Tried to get energy bins on a non-energy filter.") From bd5b7afc2d6e64bf03fb9e1400f6778baf3bbe81 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 16 Mar 2018 13:47:01 -0500 Subject: [PATCH 199/212] Fix bug related to bin ordering for mesh filters --- openmc/filter.py | 50 ++-- openmc/mesh.py | 18 ++ openmc/mgxs/mgxs.py | 16 +- openmc/tallies.py | 4 +- .../mgxs_library_mesh/results_true.dat | 256 +++++++++--------- .../tally_slice_merge/results_true.dat | 34 +-- .../tally_slice_merge/test.py | 8 +- 7 files changed, 200 insertions(+), 186 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index 8763515f4e..6cb81d97a3 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -732,37 +732,40 @@ class MeshFilter(Filter): # Filter bins for a mesh are an (x,y,z) tuple. Convert (x,y,z) to a # single bin -- this is similar to subroutine mesh_indices_to_bin in # openmc/src/mesh.F90. - if len(self.mesh.dimension) == 3: + n_dim = len(self.mesh.dimension) + if n_dim == 3: + i, j, k = filter_bin nx, ny, nz = self.mesh.dimension - val = (filter_bin[0] - 1) * ny * nz + \ - (filter_bin[1] - 1) * nz + \ - (filter_bin[2] - 1) - else: + return (i - 1) + (j - 1)*nx + (k - 1)*nx*ny + elif n_dim == 2: + i, j, *_ = filter_bin nx, ny = self.mesh.dimension - val = (filter_bin[0] - 1) * ny + \ - (filter_bin[1] - 1) - - return val + return (i - 1) + (j - 1)*nx + else: + return filter_bin[0] - 1 def get_bin(self, bin_index): cv.check_type('bin_index', bin_index, Integral) cv.check_greater_than('bin_index', bin_index, 0, equality=True) cv.check_less_than('bin_index', bin_index, self.num_bins) - # Construct 3-tuple of x,y,z cell indices for a 3D mesh - if len(self.mesh.dimension) == 3: + n_dim = len(self.mesh.dimension) + if n_dim == 3: + # Construct 3-tuple of x,y,z cell indices for a 3D mesh nx, ny, nz = self.mesh.dimension - x = bin_index / (ny * nz) - y = (bin_index - (x * ny * nz)) / nz - z = bin_index - (x * ny * nz) - (y * nz) + x = bin_index % nx + 1 + y = (bin_index % (nx * ny)) // nx + 1 + z = bin_index // (nx * ny) + 1 return (x, y, z) - # Construct 2-tuple of x,y cell indices for a 2D mesh - else: + elif n_dim == 2: + # Construct 2-tuple of x,y cell indices for a 2D mesh nx, ny = self.mesh.dimension - x = bin_index / ny - y = bin_index - (x * ny) + x = bin_index % nx + 1 + y = bin_index // nx + 1 return (x, y) + else: + return (bin_index + 1,) def get_pandas_dataframe(self, data_size, stride, **kwargs): """Builds a Pandas DataFrame for the Filter's bins. @@ -802,9 +805,10 @@ class MeshFilter(Filter): mesh_key = 'mesh {0}'.format(self.mesh.id) # Find mesh dimensions - use 3D indices for simplicity - if len(self.mesh.dimension) == 3: + n_dim = len(self.mesh.dimension) + if n_dim == 3: nx, ny, nz = self.mesh.dimension - elif len(self.mesh.dimension) == 2: + elif n_dim == 2: nx, ny = self.mesh.dimension nz = 1 else: @@ -813,7 +817,7 @@ class MeshFilter(Filter): # Generate multi-index sub-column for x-axis filter_bins = np.arange(1, nx + 1) - repeat_factor = ny * nz * stride + repeat_factor = stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) @@ -821,7 +825,7 @@ class MeshFilter(Filter): # Generate multi-index sub-column for y-axis filter_bins = np.arange(1, ny + 1) - repeat_factor = nz * stride + repeat_factor = nx * stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) @@ -829,7 +833,7 @@ class MeshFilter(Filter): # Generate multi-index sub-column for z-axis filter_bins = np.arange(1, nz + 1) - repeat_factor = stride + repeat_factor = nx * ny * stride filter_bins = np.repeat(filter_bins, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) diff --git a/openmc/mesh.py b/openmc/mesh.py index d937e25ce9..cd8eb3c5ed 100644 --- a/openmc/mesh.py +++ b/openmc/mesh.py @@ -82,6 +82,24 @@ class Mesh(IDManagerMixin): def num_mesh_cells(self): return np.prod(self._dimension) + @property + def indices(self): + ndim = len(self._dimension) + if ndim == 3: + nx, ny, nz = self.dimension + return ((x, y, z) + for z in range(1, nz + 1) + for y in range(1, ny + 1) + for x in range(1, nx + 1)) + elif ndim == 2: + nx, ny = self.dimension + return ((x, y) + for y in range(1, ny + 1) + for x in range(1, nx + 1)) + else: + nx, = self.dimension + return ((x,) for x in range(1, nx + 1)) + @name.setter def name(self, name): if name is not None: diff --git a/openmc/mgxs/mgxs.py b/openmc/mgxs/mgxs.py index ecedc8e63a..4932feff1e 100644 --- a/openmc/mgxs/mgxs.py +++ b/openmc/mgxs/mgxs.py @@ -4,7 +4,6 @@ import warnings import os import copy from abc import ABCMeta -import itertools import numpy as np import h5py @@ -937,8 +936,7 @@ class MGXS(metaclass=ABCMeta): # NOTE: This is important if tally merging was used if self.domain_type == 'mesh': filters = [_DOMAIN_TO_FILTER[self.domain_type]] - xyz = [range(1, x + 1) for x in self.domain.dimension] - filter_bins = [tuple(itertools.product(*xyz))] + filter_bins = [tuple(self.domain.indices)] elif self.domain_type != 'distribcell': filters = [_DOMAIN_TO_FILTER[self.domain_type]] filter_bins = [(self.domain.id,)] @@ -1531,8 +1529,7 @@ class MGXS(metaclass=ABCMeta): elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -1702,8 +1699,7 @@ class MGXS(metaclass=ABCMeta): domain_filter = self.xs_tally.find_filter('sum(distribcell)') subdomains = domain_filter.bins elif self.domain_type == 'mesh': - xyz = [range(1, x+1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -2342,8 +2338,7 @@ class MatrixMGXS(MGXS): elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] @@ -4530,8 +4525,7 @@ class ScatterMatrixXS(MatrixMGXS): elif self.domain_type == 'distribcell': subdomains = np.arange(self.num_subdomains, dtype=np.int) elif self.domain_type == 'mesh': - xyz = [range(1, x + 1) for x in self.domain.dimension] - subdomains = list(itertools.product(*xyz)) + subdomains = list(self.domain.indices) else: subdomains = [self.domain.id] diff --git a/openmc/tallies.py b/openmc/tallies.py index d22cfdcb46..34424acb08 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1164,9 +1164,7 @@ class Tally(IDManagerMixin): if not user_filter: # Create list of 2- or 3-tuples tuples for mesh cell bins if isinstance(self_filter, openmc.MeshFilter): - dimension = self_filter.mesh.dimension - xyz = [range(1, x+1) for x in dimension] - bins = list(product(*xyz)) + bins = list(self_filter.mesh.indices) # Create list of 2-tuples for energy boundary bins elif isinstance(self_filter, (openmc.EnergyFilter, diff --git a/tests/regression_tests/mgxs_library_mesh/results_true.dat b/tests/regression_tests/mgxs_library_mesh/results_true.dat index c167628bcc..4b9303fbf3 100644 --- a/tests/regression_tests/mgxs_library_mesh/results_true.dat +++ b/tests/regression_tests/mgxs_library_mesh/results_true.dat @@ -1,62 +1,62 @@ mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.762544 0.085298 -1 1 2 1 1 total 0.653375 0.153317 -2 2 1 1 1 total 0.644837 0.088457 +2 1 2 1 1 total 0.644837 0.088457 +1 2 1 1 1 total 0.653375 0.153317 3 2 2 1 1 total 0.676480 0.094215 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.473988 0.088732 -1 1 2 1 1 total 0.379821 0.167092 -2 2 1 1 1 total 0.399254 0.091318 +2 1 2 1 1 total 0.399254 0.091318 +1 2 1 1 1 total 0.379821 0.167092 3 2 2 1 1 total 0.424265 0.099551 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.473988 0.088732 -1 1 2 1 1 total 0.379821 0.167092 -2 2 1 1 1 total 0.399254 0.091318 +2 1 2 1 1 total 0.399254 0.091318 +1 2 1 1 1 total 0.379821 0.167092 3 2 2 1 1 total 0.424265 0.099551 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027288 0.005813 -1 1 2 1 1 total 0.019449 0.004420 -2 2 1 1 1 total 0.020262 0.003701 +2 1 2 1 1 total 0.020262 0.003701 +1 2 1 1 1 total 0.019449 0.004420 3 2 2 1 1 total 0.021266 0.002869 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.016037 0.006339 -1 1 2 1 1 total 0.012153 0.003804 -2 2 1 1 1 total 0.013018 0.003521 +2 1 2 1 1 total 0.013018 0.003521 +1 2 1 1 1 total 0.012153 0.003804 3 2 2 1 1 total 0.012965 0.002454 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.011251 0.003050 -1 1 2 1 1 total 0.007296 0.001795 -2 2 1 1 1 total 0.007243 0.001219 +2 1 2 1 1 total 0.007243 0.001219 +1 2 1 1 1 total 0.007296 0.001795 3 2 2 1 1 total 0.008301 0.001066 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027498 0.007445 -1 1 2 1 1 total 0.017912 0.004426 -2 2 1 1 1 total 0.017954 0.003077 +2 1 2 1 1 total 0.017954 0.003077 +1 2 1 1 1 total 0.017912 0.004426 3 2 2 1 1 total 0.020469 0.002617 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 2.177345e+06 589804.299388 -1 1 2 1 1 total 1.413154e+06 347806.623417 -2 2 1 1 1 total 1.404096e+06 236476.851953 +2 1 2 1 1 total 1.404096e+06 236476.851953 +1 2 1 1 1 total 1.413154e+06 347806.623417 3 2 2 1 1 total 1.608259e+06 206502.707865 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.735256 0.080216 -1 1 2 1 1 total 0.633925 0.149098 -2 2 1 1 1 total 0.624575 0.084974 +2 1 2 1 1 total 0.624575 0.084974 +1 2 1 1 1 total 0.633925 0.149098 3 2 2 1 1 total 0.655214 0.091422 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.763779 0.070696 -1 1 2 1 1 total 0.640809 0.158369 -2 2 1 1 1 total 0.628158 0.064356 +2 1 2 1 1 total 0.628158 0.064356 +1 2 1 1 1 total 0.640809 0.158369 3 2 2 1 1 total 0.645171 0.080467 mesh 1 group in group out nuclide moment mean std. dev. x y z @@ -64,14 +64,14 @@ 1 1 1 1 1 1 total P1 0.288556 0.024446 2 1 1 1 1 1 total P2 0.082441 0.011443 3 1 1 1 1 1 total P3 -0.005627 0.012638 -4 1 2 1 1 1 total P0 0.640809 0.158369 -5 1 2 1 1 1 total P1 0.273553 0.066437 -6 1 2 1 1 1 total P2 0.108446 0.024435 -7 1 2 1 1 1 total P3 0.012229 0.003785 -8 2 1 1 1 1 total P0 0.628158 0.064356 -9 2 1 1 1 1 total P1 0.245583 0.022676 -10 2 1 1 1 1 total P2 0.086370 0.007833 -11 2 1 1 1 1 total P3 0.019590 0.005345 +8 1 2 1 1 1 total P0 0.628158 0.064356 +9 1 2 1 1 1 total P1 0.245583 0.022676 +10 1 2 1 1 1 total P2 0.086370 0.007833 +11 1 2 1 1 1 total P3 0.019590 0.005345 +4 2 1 1 1 1 total P0 0.640809 0.158369 +5 2 1 1 1 1 total P1 0.273553 0.066437 +6 2 1 1 1 1 total P2 0.108446 0.024435 +7 2 1 1 1 1 total P3 0.012229 0.003785 12 2 2 1 1 1 total P0 0.645171 0.080467 13 2 2 1 1 1 total P1 0.252215 0.032154 14 2 2 1 1 1 total P2 0.089251 0.009734 @@ -82,14 +82,14 @@ 1 1 1 1 1 1 total P1 0.288556 0.024446 2 1 1 1 1 1 total P2 0.082441 0.011443 3 1 1 1 1 1 total P3 -0.005627 0.012638 -4 1 2 1 1 1 total P0 0.640809 0.158369 -5 1 2 1 1 1 total P1 0.273553 0.066437 -6 1 2 1 1 1 total P2 0.108446 0.024435 -7 1 2 1 1 1 total P3 0.012229 0.003785 -8 2 1 1 1 1 total P0 0.628158 0.064356 -9 2 1 1 1 1 total P1 0.245583 0.022676 -10 2 1 1 1 1 total P2 0.086370 0.007833 -11 2 1 1 1 1 total P3 0.019590 0.005345 +8 1 2 1 1 1 total P0 0.628158 0.064356 +9 1 2 1 1 1 total P1 0.245583 0.022676 +10 1 2 1 1 1 total P2 0.086370 0.007833 +11 1 2 1 1 1 total P3 0.019590 0.005345 +4 2 1 1 1 1 total P0 0.640809 0.158369 +5 2 1 1 1 1 total P1 0.273553 0.066437 +6 2 1 1 1 1 total P2 0.108446 0.024435 +7 2 1 1 1 1 total P3 0.012229 0.003785 12 2 2 1 1 1 total P0 0.645171 0.080467 13 2 2 1 1 1 total P1 0.252215 0.032154 14 2 2 1 1 1 total P2 0.089251 0.009734 @@ -97,20 +97,20 @@ mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 1.0 0.108337 -1 1 2 1 1 1 total 1.0 0.238517 -2 2 1 1 1 1 total 1.0 0.113128 +2 1 2 1 1 1 total 1.0 0.113128 +1 2 1 1 1 1 total 1.0 0.238517 3 2 2 1 1 1 total 1.0 0.132597 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 0.015584 0.003404 -1 1 2 1 1 1 total 0.014200 0.003676 -2 2 1 1 1 1 total 0.017684 0.002499 +2 1 2 1 1 1 total 0.017684 0.002499 +1 2 1 1 1 1 total 0.014200 0.003676 3 2 2 1 1 1 total 0.022409 0.002481 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 1.0 0.108337 -1 1 2 1 1 1 total 1.0 0.238517 -2 2 1 1 1 1 total 1.0 0.113128 +2 1 2 1 1 1 total 1.0 0.113128 +1 2 1 1 1 1 total 1.0 0.238517 3 2 2 1 1 1 total 1.0 0.132597 mesh 1 group in group out nuclide moment mean std. dev. x y z @@ -118,14 +118,14 @@ 1 1 1 1 1 1 total P1 0.277780 0.041434 2 1 1 1 1 1 total P2 0.079362 0.014706 3 1 1 1 1 1 total P3 -0.005417 0.012184 -4 1 2 1 1 1 total P0 0.633925 0.212349 -5 1 2 1 1 1 total P1 0.270615 0.089799 -6 1 2 1 1 1 total P2 0.107281 0.034246 -7 1 2 1 1 1 total P3 0.012098 0.004637 -8 2 1 1 1 1 total P0 0.624575 0.110512 -9 2 1 1 1 1 total P1 0.244182 0.041824 -10 2 1 1 1 1 total P2 0.085877 0.014634 -11 2 1 1 1 1 total P3 0.019478 0.006012 +8 1 2 1 1 1 total P0 0.624575 0.110512 +9 1 2 1 1 1 total P1 0.244182 0.041824 +10 1 2 1 1 1 total P2 0.085877 0.014634 +11 1 2 1 1 1 total P3 0.019478 0.006012 +4 2 1 1 1 1 total P0 0.633925 0.212349 +5 2 1 1 1 1 total P1 0.270615 0.089799 +6 2 1 1 1 1 total P2 0.107281 0.034246 +7 2 1 1 1 1 total P3 0.012098 0.004637 12 2 2 1 1 1 total P0 0.655214 0.126119 13 2 2 1 1 1 total P1 0.256141 0.049765 14 2 2 1 1 1 total P2 0.090641 0.016563 @@ -136,14 +136,14 @@ 1 1 1 1 1 1 total P1 0.277780 0.051210 2 1 1 1 1 1 total P2 0.079362 0.017035 3 1 1 1 1 1 total P3 -0.005417 0.012198 -4 1 2 1 1 1 total P0 0.633925 0.260681 -5 1 2 1 1 1 total P1 0.270615 0.110590 -6 1 2 1 1 1 total P2 0.107281 0.042750 -7 1 2 1 1 1 total P3 0.012098 0.005462 -8 2 1 1 1 1 total P0 0.624575 0.131169 -9 2 1 1 1 1 total P1 0.244182 0.050123 -10 2 1 1 1 1 total P2 0.085877 0.017565 -11 2 1 1 1 1 total P3 0.019478 0.006403 +8 1 2 1 1 1 total P0 0.624575 0.131169 +9 1 2 1 1 1 total P1 0.244182 0.050123 +10 1 2 1 1 1 total P2 0.085877 0.017565 +11 1 2 1 1 1 total P3 0.019478 0.006403 +4 2 1 1 1 1 total P0 0.633925 0.260681 +5 2 1 1 1 1 total P1 0.270615 0.110590 +6 2 1 1 1 1 total P2 0.107281 0.042750 +7 2 1 1 1 1 total P3 0.012098 0.005462 12 2 2 1 1 1 total P0 0.655214 0.153147 13 2 2 1 1 1 total P1 0.256141 0.060250 14 2 2 1 1 1 total P2 0.090641 0.020464 @@ -151,32 +151,32 @@ mesh 1 group out nuclide mean std. dev. x y z 0 1 1 1 1 total 1.0 0.300047 -1 1 2 1 1 total 1.0 0.262180 -2 2 1 1 1 total 1.0 0.178169 +2 1 2 1 1 total 1.0 0.178169 +1 2 1 1 1 total 1.0 0.262180 3 2 2 1 1 total 1.0 0.104797 mesh 1 group out nuclide mean std. dev. x y z 0 1 1 1 1 total 1.0 0.300047 -1 1 2 1 1 total 1.0 0.262180 -2 2 1 1 1 total 1.0 0.178169 +2 1 2 1 1 total 1.0 0.178169 +1 2 1 1 1 total 1.0 0.262180 3 2 2 1 1 total 1.0 0.108931 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 7.097008e-07 1.458546e-07 -1 1 2 1 1 total 3.984535e-07 1.157576e-07 -2 2 1 1 1 total 4.407745e-07 7.903907e-08 +2 1 2 1 1 total 4.407745e-07 7.903907e-08 +1 2 1 1 1 total 3.984535e-07 1.157576e-07 3 2 2 1 1 total 4.750476e-07 6.207437e-08 mesh 1 group in nuclide mean std. dev. x y z 0 1 1 1 1 total 0.027311 0.007397 -1 1 2 1 1 total 0.017783 0.004394 -2 2 1 1 1 total 0.017820 0.003054 +2 1 2 1 1 total 0.017820 0.003054 +1 2 1 1 1 total 0.017783 0.004394 3 2 2 1 1 total 0.020320 0.002598 mesh 1 group in group out nuclide mean std. dev. x y z 0 1 1 1 1 1 total 0.015584 0.003404 -1 1 2 1 1 1 total 0.014200 0.003676 -2 2 1 1 1 1 total 0.017684 0.002499 +2 1 2 1 1 1 total 0.017684 0.002499 +1 2 1 1 1 1 total 0.014200 0.003676 3 2 2 1 1 1 total 0.022259 0.002508 mesh 1 delayedgroup group in nuclide mean std. dev. x y z @@ -186,18 +186,18 @@ 3 1 1 1 4 1 total 0.000072 1.866015e-05 4 1 1 1 5 1 total 0.000031 7.654909e-06 5 1 1 1 6 1 total 0.000013 3.206343e-06 -6 1 2 1 1 1 total 0.000004 1.003100e-06 -7 1 2 1 2 1 total 0.000022 5.425275e-06 -8 1 2 1 3 1 total 0.000021 5.324236e-06 -9 1 2 1 4 1 total 0.000050 1.251572e-05 -10 1 2 1 5 1 total 0.000022 5.762184e-06 -11 1 2 1 6 1 total 0.000009 2.391676e-06 -12 2 1 1 1 1 total 0.000004 6.723192e-07 -13 2 1 1 2 1 total 0.000022 3.706235e-06 -14 2 1 1 3 1 total 0.000022 3.674263e-06 -15 2 1 1 4 1 total 0.000052 8.774048e-06 -16 2 1 1 5 1 total 0.000024 4.168024e-06 -17 2 1 1 6 1 total 0.000010 1.726268e-06 +12 1 2 1 1 1 total 0.000004 6.723192e-07 +13 1 2 1 2 1 total 0.000022 3.706235e-06 +14 1 2 1 3 1 total 0.000022 3.674263e-06 +15 1 2 1 4 1 total 0.000052 8.774048e-06 +16 1 2 1 5 1 total 0.000024 4.168024e-06 +17 1 2 1 6 1 total 0.000010 1.726268e-06 +6 2 1 1 1 1 total 0.000004 1.003100e-06 +7 2 1 1 2 1 total 0.000022 5.425275e-06 +8 2 1 1 3 1 total 0.000021 5.324236e-06 +9 2 1 1 4 1 total 0.000050 1.251572e-05 +10 2 1 1 5 1 total 0.000022 5.762184e-06 +11 2 1 1 6 1 total 0.000009 2.391676e-06 18 2 2 1 1 1 total 0.000005 5.962367e-07 19 2 2 1 2 1 total 0.000025 3.200900e-06 20 2 2 1 3 1 total 0.000025 3.127442e-06 @@ -212,18 +212,18 @@ 3 1 1 1 4 1 total 0.0 0.000000 4 1 1 1 5 1 total 0.0 0.000000 5 1 1 1 6 1 total 0.0 0.000000 -6 1 2 1 1 1 total 0.0 0.000000 -7 1 2 1 2 1 total 0.0 0.000000 -8 1 2 1 3 1 total 0.0 0.000000 -9 1 2 1 4 1 total 0.0 0.000000 -10 1 2 1 5 1 total 0.0 0.000000 -11 1 2 1 6 1 total 0.0 0.000000 -12 2 1 1 1 1 total 0.0 0.000000 -13 2 1 1 2 1 total 0.0 0.000000 -14 2 1 1 3 1 total 0.0 0.000000 -15 2 1 1 4 1 total 0.0 0.000000 -16 2 1 1 5 1 total 0.0 0.000000 -17 2 1 1 6 1 total 0.0 0.000000 +12 1 2 1 1 1 total 0.0 0.000000 +13 1 2 1 2 1 total 0.0 0.000000 +14 1 2 1 3 1 total 0.0 0.000000 +15 1 2 1 4 1 total 0.0 0.000000 +16 1 2 1 5 1 total 0.0 0.000000 +17 1 2 1 6 1 total 0.0 0.000000 +6 2 1 1 1 1 total 0.0 0.000000 +7 2 1 1 2 1 total 0.0 0.000000 +8 2 1 1 3 1 total 0.0 0.000000 +9 2 1 1 4 1 total 0.0 0.000000 +10 2 1 1 5 1 total 0.0 0.000000 +11 2 1 1 6 1 total 0.0 0.000000 18 2 2 1 1 1 total 0.0 0.000000 19 2 2 1 2 1 total 0.0 0.000000 20 2 2 1 3 1 total 1.0 1.414214 @@ -238,18 +238,18 @@ 3 1 1 1 4 1 total 0.002629 0.000950 4 1 1 1 5 1 total 0.001125 0.000398 5 1 1 1 6 1 total 0.000470 0.000166 -6 1 2 1 1 1 total 0.000228 0.000057 -7 1 2 1 2 1 total 0.001222 0.000309 -8 1 2 1 3 1 total 0.001193 0.000304 -9 1 2 1 4 1 total 0.002780 0.000713 -10 1 2 1 5 1 total 0.001250 0.000328 -11 1 2 1 6 1 total 0.000520 0.000136 -12 2 1 1 1 1 total 0.000225 0.000044 -13 2 1 1 2 1 total 0.001232 0.000242 -14 2 1 1 3 1 total 0.001216 0.000239 -15 2 1 1 4 1 total 0.002882 0.000570 -16 2 1 1 5 1 total 0.001345 0.000270 -17 2 1 1 6 1 total 0.000558 0.000112 +12 1 2 1 1 1 total 0.000225 0.000044 +13 1 2 1 2 1 total 0.001232 0.000242 +14 1 2 1 3 1 total 0.001216 0.000239 +15 1 2 1 4 1 total 0.002882 0.000570 +16 1 2 1 5 1 total 0.001345 0.000270 +17 1 2 1 6 1 total 0.000558 0.000112 +6 2 1 1 1 1 total 0.000228 0.000057 +7 2 1 1 2 1 total 0.001222 0.000309 +8 2 1 1 3 1 total 0.001193 0.000304 +9 2 1 1 4 1 total 0.002780 0.000713 +10 2 1 1 5 1 total 0.001250 0.000328 +11 2 1 1 6 1 total 0.000520 0.000136 18 2 2 1 1 1 total 0.000227 0.000027 19 2 2 1 2 1 total 0.001225 0.000143 20 2 2 1 3 1 total 0.001201 0.000140 @@ -264,18 +264,18 @@ 3 1 1 1 4 1 total 0.304289 0.106753 4 1 1 1 5 1 total 0.855760 0.286466 5 1 1 1 6 1 total 2.874120 0.965609 -6 1 2 1 1 1 total 0.013357 0.003345 -7 1 2 1 2 1 total 0.032590 0.008273 -8 1 2 1 3 1 total 0.121103 0.031074 -9 1 2 1 4 1 total 0.306111 0.080011 -10 1 2 1 5 1 total 0.862660 0.235694 -11 1 2 1 6 1 total 2.897534 0.788926 -12 2 1 1 1 1 total 0.013367 0.002548 -13 2 1 1 2 1 total 0.032520 0.006266 -14 2 1 1 3 1 total 0.121250 0.023544 -15 2 1 1 4 1 total 0.307552 0.060464 -16 2 1 1 5 1 total 0.867665 0.175131 -17 2 1 1 6 1 total 2.914635 0.587161 +12 1 2 1 1 1 total 0.013367 0.002548 +13 1 2 1 2 1 total 0.032520 0.006266 +14 1 2 1 3 1 total 0.121250 0.023544 +15 1 2 1 4 1 total 0.307552 0.060464 +16 1 2 1 5 1 total 0.867665 0.175131 +17 1 2 1 6 1 total 2.914635 0.587161 +6 2 1 1 1 1 total 0.013357 0.003345 +7 2 1 1 2 1 total 0.032590 0.008273 +8 2 1 1 3 1 total 0.121103 0.031074 +9 2 1 1 4 1 total 0.306111 0.080011 +10 2 1 1 5 1 total 0.862660 0.235694 +11 2 1 1 6 1 total 2.897534 0.788926 18 2 2 1 1 1 total 0.013360 0.001587 19 2 2 1 2 1 total 0.032564 0.003810 20 2 2 1 3 1 total 0.121158 0.014038 @@ -290,18 +290,18 @@ 3 1 1 1 4 1 1 total 0.00000 0.000000 4 1 1 1 5 1 1 total 0.00000 0.000000 5 1 1 1 6 1 1 total 0.00000 0.000000 -6 1 2 1 1 1 1 total 0.00000 0.000000 -7 1 2 1 2 1 1 total 0.00000 0.000000 -8 1 2 1 3 1 1 total 0.00000 0.000000 -9 1 2 1 4 1 1 total 0.00000 0.000000 -10 1 2 1 5 1 1 total 0.00000 0.000000 -11 1 2 1 6 1 1 total 0.00000 0.000000 -12 2 1 1 1 1 1 total 0.00000 0.000000 -13 2 1 1 2 1 1 total 0.00000 0.000000 -14 2 1 1 3 1 1 total 0.00000 0.000000 -15 2 1 1 4 1 1 total 0.00000 0.000000 -16 2 1 1 5 1 1 total 0.00000 0.000000 -17 2 1 1 6 1 1 total 0.00000 0.000000 +12 1 2 1 1 1 1 total 0.00000 0.000000 +13 1 2 1 2 1 1 total 0.00000 0.000000 +14 1 2 1 3 1 1 total 0.00000 0.000000 +15 1 2 1 4 1 1 total 0.00000 0.000000 +16 1 2 1 5 1 1 total 0.00000 0.000000 +17 1 2 1 6 1 1 total 0.00000 0.000000 +6 2 1 1 1 1 1 total 0.00000 0.000000 +7 2 1 1 2 1 1 total 0.00000 0.000000 +8 2 1 1 3 1 1 total 0.00000 0.000000 +9 2 1 1 4 1 1 total 0.00000 0.000000 +10 2 1 1 5 1 1 total 0.00000 0.000000 +11 2 1 1 6 1 1 total 0.00000 0.000000 18 2 2 1 1 1 1 total 0.00000 0.000000 19 2 2 1 2 1 1 total 0.00000 0.000000 20 2 2 1 3 1 1 total 0.00015 0.000151 diff --git a/tests/regression_tests/tally_slice_merge/results_true.dat b/tests/regression_tests/tally_slice_merge/results_true.dat index 4f1d6c6e2c..461c4faa87 100644 --- a/tests/regression_tests/tally_slice_merge/results_true.dat +++ b/tests/regression_tests/tally_slice_merge/results_true.dat @@ -48,20 +48,20 @@ 13 (500, 5000, 50000) 6.25e-01 2.00e+07 U235 nu-fission 0.00e+00 0.00e+00 14 (500, 5000, 50000) 6.25e-01 2.00e+07 U238 fission 0.00e+00 0.00e+00 15 (500, 5000, 50000) 6.25e-01 2.00e+07 U238 nu-fission 0.00e+00 0.00e+00 - sum(mesh) energy low [eV] energy high [eV] nuclide score mean std. dev. -0 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U235 fission 1.48e-02 3.65e-03 -1 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U235 nu-fission 3.60e-02 8.90e-03 -2 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U238 fission 2.06e-08 4.98e-09 -3 ((1, 1, 1), (1, 2, 1)) 0.00e+00 6.25e-01 U238 nu-fission 5.14e-08 1.24e-08 -4 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U235 fission 2.23e-03 3.92e-04 -5 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U235 nu-fission 5.45e-03 9.56e-04 -6 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U238 fission 5.58e-04 2.08e-04 -7 ((1, 1, 1), (1, 2, 1)) 6.25e-01 2.00e+07 U238 nu-fission 1.50e-03 5.43e-04 -8 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U235 fission 2.56e-02 5.50e-03 -9 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U235 nu-fission 6.24e-02 1.34e-02 -10 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U238 fission 3.55e-08 7.70e-09 -11 ((2, 1, 1), (2, 2, 1)) 0.00e+00 6.25e-01 U238 nu-fission 8.85e-08 1.92e-08 -12 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U235 fission 5.01e-03 1.38e-03 -13 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U235 nu-fission 1.22e-02 3.37e-03 -14 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U238 fission 2.40e-03 2.69e-04 -15 ((2, 1, 1), (2, 2, 1)) 6.25e-01 2.00e+07 U238 nu-fission 6.60e-03 7.63e-04 + sum(mesh) energy low [eV] energy high [eV] nuclide score mean std. dev. +0 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U235 fission 0.00e+00 0.00e+00 +1 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U235 nu-fission 0.00e+00 0.00e+00 +2 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U238 fission 0.00e+00 0.00e+00 +3 ((1, 1), (1, 2)) 0.00e+00 6.25e-01 U238 nu-fission 0.00e+00 0.00e+00 +4 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U235 fission 1.60e-04 1.60e-04 +5 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U235 nu-fission 3.91e-04 3.91e-04 +6 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U238 fission 5.12e-05 5.12e-05 +7 ((1, 1), (1, 2)) 6.25e-01 2.00e+07 U238 nu-fission 1.36e-04 1.36e-04 +8 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U235 fission 4.04e-02 6.60e-03 +9 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U235 nu-fission 9.85e-02 1.61e-02 +10 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U238 fission 5.61e-08 9.18e-09 +11 ((2, 1), (2, 2)) 0.00e+00 6.25e-01 U238 nu-fission 1.40e-07 2.29e-08 +12 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U235 fission 7.08e-03 1.43e-03 +13 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U235 nu-fission 1.73e-02 3.48e-03 +14 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U238 fission 2.91e-03 3.36e-04 +15 ((2, 1), (2, 2)) 6.25e-01 2.00e+07 U238 nu-fission 7.96e-03 9.27e-04 diff --git a/tests/regression_tests/tally_slice_merge/test.py b/tests/regression_tests/tally_slice_merge/test.py index f79c8b2685..e52d0fde49 100644 --- a/tests/regression_tests/tally_slice_merge/test.py +++ b/tests/regression_tests/tally_slice_merge/test.py @@ -126,10 +126,10 @@ class TallySliceMergeTestHarness(PyAPITestHarness): # Sum up a few subdomains from the distribcell tally sum1 = distribcell_tally.summation(filter_type=openmc.DistribcellFilter, - filter_bins=[0,100,2000,30000]) + filter_bins=[0, 100, 2000, 30000]) # Sum up a few subdomains from the distribcell tally sum2 = distribcell_tally.summation(filter_type=openmc.DistribcellFilter, - filter_bins=[500,5000,50000]) + filter_bins=[500, 5000, 50000]) # Merge the distribcell tally slices merge_tally = sum1.merge(sum2) @@ -143,10 +143,10 @@ class TallySliceMergeTestHarness(PyAPITestHarness): # Sum up a few subdomains from the mesh tally sum1 = mesh_tally.summation(filter_type=openmc.MeshFilter, - filter_bins=[(1,1,1), (1,2,1)]) + filter_bins=[(1, 1), (1, 2)]) # Sum up a few subdomains from the mesh tally sum2 = mesh_tally.summation(filter_type=openmc.MeshFilter, - filter_bins=[(2,1,1), (2,2,1)]) + filter_bins=[(2, 1), (2, 2)]) # Merge the mesh tally slices merge_tally = sum1.merge(sum2) From 0b6333810f7f73317f459a701a7d5cbd487f31ff Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 16 Mar 2018 14:07:38 -0500 Subject: [PATCH 200/212] Avoid divide-by-zero warnings in tally arithmetic --- openmc/tallies.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/openmc/tallies.py b/openmc/tallies.py index 34424acb08..d8bc2136a1 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -1674,19 +1674,22 @@ class Tally(IDManagerMixin): new_tally._std_dev = np.sqrt(data['self']['std. dev.']**2 + data['other']['std. dev.']**2) elif binary_op == '*': - self_rel_err = data['self']['std. dev.'] / data['self']['mean'] - other_rel_err = data['other']['std. dev.'] / data['other']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + self_rel_err = data['self']['std. dev.'] / data['self']['mean'] + other_rel_err = data['other']['std. dev.'] / data['other']['mean'] new_tally._mean = data['self']['mean'] * data['other']['mean'] new_tally._std_dev = np.abs(new_tally.mean) * \ np.sqrt(self_rel_err**2 + other_rel_err**2) elif binary_op == '/': - self_rel_err = data['self']['std. dev.'] / data['self']['mean'] - other_rel_err = data['other']['std. dev.'] / data['other']['mean'] - new_tally._mean = data['self']['mean'] / data['other']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + self_rel_err = data['self']['std. dev.'] / data['self']['mean'] + other_rel_err = data['other']['std. dev.'] / data['other']['mean'] + new_tally._mean = data['self']['mean'] / data['other']['mean'] new_tally._std_dev = np.abs(new_tally.mean) * \ np.sqrt(self_rel_err**2 + other_rel_err**2) elif binary_op == '^': - mean_ratio = data['other']['mean'] / data['self']['mean'] + with np.errstate(divide='ignore', invalid='ignore'): + mean_ratio = data['other']['mean'] / data['self']['mean'] first_term = mean_ratio * data['self']['std. dev.'] second_term = \ np.log(data['self']['mean']) * data['other']['std. dev.'] From c83b89086912d2363778b609224c42b7acab7038 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Mar 2018 10:13:51 -0500 Subject: [PATCH 201/212] Use ufloat for stochastic volume results --- openmc/cell.py | 4 +- openmc/data/decay.py | 5 +- openmc/material.py | 2 +- openmc/universe.py | 4 +- openmc/volume.py | 10 ++-- .../volume_calc/results_true.dat | 54 +++++++++---------- tests/regression_tests/volume_calc/test.py | 3 +- 7 files changed, 39 insertions(+), 43 deletions(-) diff --git a/openmc/cell.py b/openmc/cell.py index c7587e136a..cbfd74b21b 100644 --- a/openmc/cell.py +++ b/openmc/cell.py @@ -295,7 +295,7 @@ class Cell(IDManagerMixin): """ if volume_calc.domain_type == 'cell': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this cell.') @@ -335,7 +335,7 @@ class Cell(IDManagerMixin): volume = self.volume for name, atoms in self._atoms.items(): nuclide = openmc.Nuclide(name) - density = 1.0e-24 * atoms[0]/volume # density in atoms/b-cm + density = 1.0e-24 * atoms.n/volume # density in atoms/b-cm nuclides[name] = (nuclide, density) else: raise RuntimeError( diff --git a/openmc/data/decay.py b/openmc/data/decay.py index fa18759396..bbb059f4fa 100644 --- a/openmc/data/decay.py +++ b/openmc/data/decay.py @@ -7,10 +7,7 @@ import re from warnings import warn import numpy as np -try: - from uncertainties import ufloat, unumpy, UFloat -except ImportError: - ufloat = UFloat = namedtuple('UFloat', ['nominal_value', 'std_dev']) +from uncertainties import ufloat, unumpy, UFloat import openmc.checkvalue as cv from openmc.mixin import EqualityMixin diff --git a/openmc/material.py b/openmc/material.py index 88479d8df6..6bfe58f4ac 100644 --- a/openmc/material.py +++ b/openmc/material.py @@ -313,7 +313,7 @@ class Material(IDManagerMixin): """ if volume_calc.domain_type == 'material': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this material.') diff --git a/openmc/universe.py b/openmc/universe.py index 77138adcce..294b114dd2 100644 --- a/openmc/universe.py +++ b/openmc/universe.py @@ -145,7 +145,7 @@ class Universe(IDManagerMixin): """ if volume_calc.domain_type == 'universe': if self.id in volume_calc.volumes: - self._volume = volume_calc.volumes[self.id][0] + self._volume = volume_calc.volumes[self.id].n self._atoms = volume_calc.atoms[self.id] else: raise ValueError('No volume information found for this universe.') @@ -406,7 +406,7 @@ class Universe(IDManagerMixin): volume = self.volume for name, atoms in self._atoms.items(): nuclide = openmc.Nuclide(name) - density = 1.0e-24 * atoms[0]/volume # density in atoms/b-cm + density = 1.0e-24 * atoms.n/volume # density in atoms/b-cm nuclides[name] = (nuclide, density) else: raise RuntimeError( diff --git a/openmc/volume.py b/openmc/volume.py index d61093a178..af7c356aed 100644 --- a/openmc/volume.py +++ b/openmc/volume.py @@ -7,6 +7,7 @@ import warnings import numpy as np import pandas as pd import h5py +from uncertainties import ufloat import openmc import openmc.checkvalue as cv @@ -137,11 +138,10 @@ class VolumeCalculation(object): @property def atoms_dataframe(self): items = [] - columns = [self.domain_type.capitalize(), 'Nuclide', 'Atoms', - 'Uncertainty'] + columns = [self.domain_type.capitalize(), 'Nuclide', 'Atoms'] for uid, atoms_dict in self.atoms.items(): for name, atoms in atoms_dict.items(): - items.append((uid, name, atoms[0], atoms[1])) + items.append((uid, name, atoms)) return pd.DataFrame.from_records(items, columns=columns) @@ -211,13 +211,13 @@ class VolumeCalculation(object): domain_id = int(obj_name[7:]) ids.append(domain_id) group = f[obj_name] - volume = tuple(group['volume'].value) + volume = ufloat(*group['volume'].value) nucnames = group['nuclides'].value atoms_ = group['atoms'].value atom_dict = OrderedDict() for name_i, atoms_i in zip(nucnames, atoms_): - atom_dict[name_i.decode()] = tuple(atoms_i) + atom_dict[name_i.decode()] = ufloat(*atoms_i) volumes[domain_id] = volume atoms[domain_id] = atom_dict diff --git a/tests/regression_tests/volume_calc/results_true.dat b/tests/regression_tests/volume_calc/results_true.dat index 8eb2a61acf..466139cd68 100644 --- a/tests/regression_tests/volume_calc/results_true.dat +++ b/tests/regression_tests/volume_calc/results_true.dat @@ -1,30 +1,30 @@ Volume calculation 0 -Domain 1: 31.4693 +/- 0.0721 cm^3 -Domain 2: 2.0933 +/- 0.0310 cm^3 -Domain 3: 2.0486 +/- 0.0307 cm^3 - Cell Nuclide Atoms Uncertainty -0 1 U235 3.481769e+23 7.979991e+20 -1 1 Mo99 3.481769e+22 7.979991e+19 -2 2 H1 1.399770e+23 2.072914e+21 -3 2 O16 6.998852e+22 1.036457e+21 -4 2 B10 6.998852e+18 1.036457e+17 -5 3 H1 1.369920e+23 2.051689e+21 -6 3 O16 6.849599e+22 1.025844e+21 -7 3 B10 6.849599e+18 1.025844e+17 +Domain 1: 31.47+/-0.07 cm^3 +Domain 2: 2.093+/-0.031 cm^3 +Domain 3: 2.049+/-0.031 cm^3 + Cell Nuclide Atoms +0 1 U235 (3.482+/-0.008)e+23 +1 1 Mo99 (3.482+/-0.008)e+22 +2 2 H1 (1.400+/-0.021)e+23 +3 2 O16 (7.00+/-0.10)e+22 +4 2 B10 (7.00+/-0.10)e+18 +5 3 H1 (1.370+/-0.021)e+23 +6 3 O16 (6.85+/-0.10)e+22 +7 3 B10 (6.85+/-0.10)e+18 Volume calculation 1 -Domain 1: 4.1419 +/- 0.0426 cm^3 -Domain 2: 31.4693 +/- 0.0721 cm^3 - Material Nuclide Atoms Uncertainty -0 1 H1 2.769690e+23 2.850067e+21 -1 1 O16 1.384845e+23 1.425034e+21 -2 1 B10 1.384845e+19 1.425034e+17 -3 2 U235 3.481769e+23 7.979991e+20 -4 2 Mo99 3.481769e+22 7.979991e+19 +Domain 1: 4.14+/-0.04 cm^3 +Domain 2: 31.47+/-0.07 cm^3 + Material Nuclide Atoms +0 1 H1 (2.770+/-0.029)e+23 +1 1 O16 (1.385+/-0.014)e+23 +2 1 B10 (1.385+/-0.014)e+19 +3 2 U235 (3.482+/-0.008)e+23 +4 2 Mo99 (3.482+/-0.008)e+22 Volume calculation 2 -Domain 0: 35.6112 +/- 0.0664 cm^3 - Universe Nuclide Atoms Uncertainty -0 0 H1 2.769690e+23 2.850067e+21 -1 0 O16 1.384845e+23 1.425034e+21 -2 0 B10 1.384845e+19 1.425034e+17 -3 0 U235 3.481769e+23 7.979991e+20 -4 0 Mo99 3.481769e+22 7.979991e+19 +Domain 0: 35.61+/-0.07 cm^3 + Universe Nuclide Atoms +0 0 H1 (2.770+/-0.029)e+23 +1 0 O16 (1.385+/-0.014)e+23 +2 0 B10 (1.385+/-0.014)e+19 +3 0 U235 (3.482+/-0.008)e+23 +4 0 Mo99 (3.482+/-0.008)e+22 diff --git a/tests/regression_tests/volume_calc/test.py b/tests/regression_tests/volume_calc/test.py index a6b62b9be9..fda4b33210 100644 --- a/tests/regression_tests/volume_calc/test.py +++ b/tests/regression_tests/volume_calc/test.py @@ -64,8 +64,7 @@ class VolumeTest(PyAPITestHarness): # Write cell volumes and total # of atoms for each nuclide for uid, volume in sorted(volume_calc.volumes.items()): - outstr += 'Domain {0}: {1[0]:.4f} +/- {1[1]:.4f} cm^3\n'.format( - uid, volume) + outstr += 'Domain {}: {} cm^3\n'.format(uid, volume) outstr += str(volume_calc.atoms_dataframe) + '\n' return outstr From 5dc25569f2b54d87e6c9cf7b263c06cdb1914094 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Mar 2018 10:15:08 -0500 Subject: [PATCH 202/212] Use latest HDF5 format for openmc-get-jeff-data --- scripts/openmc-get-jeff-data | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/openmc-get-jeff-data b/scripts/openmc-get-jeff-data index 9f426a4930..03b58163b0 100755 --- a/scripts/openmc-get-jeff-data +++ b/scripts/openmc-get-jeff-data @@ -41,7 +41,7 @@ parser.add_argument('-b', '--batch', action='store_true', parser.add_argument('-d', '--destination', default='jeff-3.2-hdf5', help='Directory to create new library in') parser.add_argument('--libver', choices=['earliest', 'latest'], - default='earliest', help="Output HDF5 versioning. Use " + default='latest', help="Output HDF5 versioning. Use " "'earliest' for backwards compatibility or 'latest' for " "performance") args = parser.parse_args() From efade329a8ccf2ca56ffda48e2dfe64c6a6aab43 Mon Sep 17 00:00:00 2001 From: Sterling Harper Date: Mon, 19 Mar 2018 12:55:46 -0400 Subject: [PATCH 203/212] Address #983 comments --- openmc/data/multipole.py | 55 ++++++++++++------------- tests/unit_tests/test_data_multipole.py | 4 +- 2 files changed, 29 insertions(+), 30 deletions(-) diff --git a/openmc/data/multipole.py b/openmc/data/multipole.py index ac1e93447d..f7a78d9532 100644 --- a/openmc/data/multipole.py +++ b/openmc/data/multipole.py @@ -652,7 +652,7 @@ class WindowedMultipole(EqualityMixin): fun = np.vectorize(lambda x: self._evaluate(x, T)) return fun(E) - def to_hdf5(self, path, libver='earliest'): + def export_to_hdf5(self, path, libver='earliest'): """Export windowed multipole data to an HDF5 file. Parameters @@ -666,33 +666,32 @@ class WindowedMultipole(EqualityMixin): """ # Open file and write version. - f = h5py.File(path, 'w', libver=libver) - f.create_dataset('version', (1, ), dtype='S10') - f['version'][:] = WMP_VERSION.encode('ASCII') + with h5py.File(path, 'w', libver=libver) as f: + f.create_dataset('version', (1, ), dtype='S10') + f['version'][:] = WMP_VERSION.encode('ASCII') - # Make a nuclide group. - g = f.create_group('nuclide') + # Make a nuclide group. + g = f.create_group('nuclide') - # Write scalars. - if self.formalism == 'MLBW': - g.create_dataset('formalism', - data=np.array(_FORM_MLBW, dtype=np.int32)) - else: - # Assume RM. - g.create_dataset('formalism', - data=np.array(_FORM_RM, dtype=np.int32)) - g.create_dataset('spacing', data=np.array(self.spacing)) - g.create_dataset('sqrtAWR', data=np.array(self.sqrtAWR)) - g.create_dataset('start_E', data=np.array(self.start_E)) - g.create_dataset('end_E', data=np.array(self.end_E)) + # Write scalars. + if self.formalism == 'MLBW': + g.create_dataset('formalism', + data=np.array(_FORM_MLBW, dtype=np.int32)) + else: + # Assume RM. + g.create_dataset('formalism', + data=np.array(_FORM_RM, dtype=np.int32)) + g.create_dataset('spacing', data=np.array(self.spacing)) + g.create_dataset('sqrtAWR', data=np.array(self.sqrtAWR)) + g.create_dataset('start_E', data=np.array(self.start_E)) + g.create_dataset('end_E', data=np.array(self.end_E)) - # Write arrays. - g.create_dataset('data', data=self.data) - g.create_dataset('l_value', data=self.l_value) - g.create_dataset('pseudo_K0RS', data=self.pseudo_k0RS) - g.create_dataset('w_start', data=self.w_start) - g.create_dataset('w_end', data=self.w_end) - g.create_dataset('broaden_poly', data=self.broaden_poly) - g.create_dataset('curvefit', data=self.curvefit) - - f.close() + # Write arrays. + g.create_dataset('data', data=self.data) + g.create_dataset('l_value', data=self.l_value) + g.create_dataset('pseudo_K0RS', data=self.pseudo_k0RS) + g.create_dataset('w_start', data=self.w_start) + g.create_dataset('w_end', data=self.w_end) + g.create_dataset('broaden_poly', + data=self.broaden_poly.astype(np.int8)) + g.create_dataset('curvefit', data=self.curvefit) diff --git a/tests/unit_tests/test_data_multipole.py b/tests/unit_tests/test_data_multipole.py index de7c1cc931..a1cc5bc02c 100644 --- a/tests/unit_tests/test_data_multipole.py +++ b/tests/unit_tests/test_data_multipole.py @@ -58,7 +58,7 @@ def test_high_l(fe56): assert total[0] == pytest.approx(27.85535792368082) -def test_to_hdf5(tmpdir, u235): +def test_export_to_hdf5(tmpdir, u235): filename = str(tmpdir.join('092235.h5')) - u235.to_hdf5(filename) + u235.export_to_hdf5(filename) assert os.path.exists(filename) From 85af75c459da55b3d77cf15e5b556b61ca97aa4b Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Mar 2018 13:58:58 -0500 Subject: [PATCH 204/212] Address comments on #985 --- openmc/filter.py | 4 ++-- openmc/plots.py | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index 6cb81d97a3..26629dafe0 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -753,7 +753,7 @@ class MeshFilter(Filter): if n_dim == 3: # Construct 3-tuple of x,y,z cell indices for a 3D mesh nx, ny, nz = self.mesh.dimension - x = bin_index % nx + 1 + x = (bin_index % nx) + 1 y = (bin_index % (nx * ny)) // nx + 1 z = bin_index // (nx * ny) + 1 return (x, y, z) @@ -761,7 +761,7 @@ class MeshFilter(Filter): elif n_dim == 2: # Construct 2-tuple of x,y cell indices for a 2D mesh nx, ny = self.mesh.dimension - x = bin_index % nx + 1 + x = (bin_index % nx) + 1 y = bin_index // nx + 1 return (x, y) else: diff --git a/openmc/plots.py b/openmc/plots.py index a948c2a48e..8eff78b1d9 100644 --- a/openmc/plots.py +++ b/openmc/plots.py @@ -651,9 +651,16 @@ class Plot(IDManagerMixin): return element - def to_image(self, openmc_exec='openmc', cwd='.', convert_exec='convert'): + def to_ipython_image(self, openmc_exec='openmc', cwd='.', + convert_exec='convert'): """Render plot as an image + This method runs OpenMC in plotting mode to produce a bitmap image which + is then converted to a .png file and loaded in as an + :class:`IPython.display.Image` object. As such, it requires that your + model geometry, materials, and settings have already been exported to + XML. + Parameters ---------- openmc_exec : str From 794ac9255ae077a1dc6e496f24df194d5d669099 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Mar 2018 14:07:42 -0500 Subject: [PATCH 205/212] Add initial Fortran implementation of MeshSurfaceFilter --- CMakeLists.txt | 1 + src/constants.F90 | 5 +- src/input_xml.F90 | 11 +- src/tallies/tally_filter.F90 | 5 + src/tallies/tally_filter_mesh.F90 | 3 - src/tallies/tally_filter_meshsurface.F90 | 392 +++++++++++++++++++++++ src/tallies/tally_header.F90 | 2 + 7 files changed, 411 insertions(+), 8 deletions(-) create mode 100644 src/tallies/tally_filter_meshsurface.F90 diff --git a/CMakeLists.txt b/CMakeLists.txt index be62dcd57b..9517fe2ec3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -422,6 +422,7 @@ set(LIBOPENMC_FORTRAN_SRC src/tallies/tally_filter_energyfunc.F90 src/tallies/tally_filter_material.F90 src/tallies/tally_filter_mesh.F90 + src/tallies/tally_filter_meshsurface.F90 src/tallies/tally_filter_mu.F90 src/tallies/tally_filter_polar.F90 src/tallies/tally_filter_surface.F90 diff --git a/src/constants.F90 b/src/constants.F90 index 3334a4cc76..75a9471490 100644 --- a/src/constants.F90 +++ b/src/constants.F90 @@ -358,7 +358,7 @@ module constants integer, parameter :: NO_BIN_FOUND = -1 ! Tally filter and map types - integer, parameter :: N_FILTER_TYPES = 15 + integer, parameter :: N_FILTER_TYPES = 16 integer, parameter :: & FILTER_UNIVERSE = 1, & FILTER_MATERIAL = 2, & @@ -374,7 +374,8 @@ module constants FILTER_AZIMUTHAL = 12, & FILTER_DELAYEDGROUP = 13, & FILTER_ENERGYFUNCTION = 14, & - FILTER_CELLFROM = 15 + FILTER_CELLFROM = 15, & + FILTER_MESHSURFACE = 16 ! Mesh types integer, parameter :: & diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 918d471d3c..792450e517 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -10,7 +10,7 @@ module input_xml use distribution_multivariate use distribution_univariate use endf, only: reaction_name - use error, only: fatal_error, warning, write_message + use error, only: fatal_error, warning, write_message, openmc_err_msg use geometry, only: calc_offsets, maximum_levels, count_instance, & neighbor_lists use geometry_header @@ -2358,13 +2358,13 @@ contains call get_node_value(node_filt, "type", temp_str) temp_str = to_lower(temp_str) - ! Determine number of bins + ! Make sure bins have been set select case(temp_str) case ("energy", "energyout", "mu", "polar", "azimuthal") if (.not. check_for_node(node_filt, "bins")) then call fatal_error("Bins not set in filter " // trim(to_str(filter_id))) end if - case ("mesh", "universe", "material", "cell", "distribcell", & + case ("mesh", "meshsurface", "universe", "material", "cell", "distribcell", & "cellborn", "cellfrom", "surface", "delayedgroup") if (.not. check_for_node(node_filt, "bins")) then call fatal_error("Bins not set in filter " // trim(to_str(filter_id))) @@ -2373,6 +2373,9 @@ contains ! Allocate according to the filter type err = openmc_filter_set_type(i_start + i - 1, to_c_string(temp_str)) + if (err /= 0) then + call fatal_error(to_f_string(openmc_err_msg)) + end if ! Read filter data from XML call f % obj % from_xml(node_filt) @@ -2923,6 +2926,8 @@ contains ! Set filters err = openmc_tally_set_filters(i_start + i - 1, n_filter, temp_filter) deallocate(temp_filter) + else + t % score_bins(j) = SCORE_CURRENT end if case ('events') diff --git a/src/tallies/tally_filter.F90 b/src/tallies/tally_filter.F90 index 587f8dd902..3d6eaaef21 100644 --- a/src/tallies/tally_filter.F90 +++ b/src/tallies/tally_filter.F90 @@ -19,6 +19,7 @@ module tally_filter use tally_filter_energyfunc use tally_filter_material use tally_filter_mesh + use tally_filter_meshsurface use tally_filter_mu use tally_filter_polar use tally_filter_surface @@ -67,6 +68,8 @@ contains type_ = 'material' type is (MeshFilter) type_ = 'mesh' + type is (MeshSurfaceFilter) + type_ = 'meshsurface' type is (MuFilter) type_ = 'mu' type is (PolarFilter) @@ -136,6 +139,8 @@ contains allocate(MaterialFilter :: filters(index) % obj) case ('mesh') allocate(MeshFilter :: filters(index) % obj) + case ('meshsurface') + allocate(MeshSurfaceFilter :: filters(index) % obj) case ('mu') allocate(MuFilter :: filters(index) % obj) case ('polar') diff --git a/src/tallies/tally_filter_mesh.F90 b/src/tallies/tally_filter_mesh.F90 index 2092e7e717..3c0e6250c2 100644 --- a/src/tallies/tally_filter_mesh.F90 +++ b/src/tallies/tally_filter_mesh.F90 @@ -84,7 +84,6 @@ contains integer :: ijk1(3) ! indices of ending coordinates integer :: search_iter ! loop count for intersection search integer :: bin - real(8) :: weight ! weight to be pushed back real(8) :: uvw(3) ! cosine of angle of particle real(8) :: xyz0(3) ! starting/intermediate coordinates real(8) :: xyz1(3) ! ending coordinates of particle @@ -96,8 +95,6 @@ contains logical :: end_in_mesh ! ending coordinates inside mesh? type(RegularMesh), pointer :: m - weight = ERROR_REAL - ! Get a pointer to the mesh. m => meshes(this % mesh) n = m % n_dimension diff --git a/src/tallies/tally_filter_meshsurface.F90 b/src/tallies/tally_filter_meshsurface.F90 new file mode 100644 index 0000000000..e45261f440 --- /dev/null +++ b/src/tallies/tally_filter_meshsurface.F90 @@ -0,0 +1,392 @@ +module tally_filter_meshsurface + + use, intrinsic :: ISO_C_BINDING + + use hdf5 + + use constants + use dict_header, only: EMPTY + use error + use mesh_header, only: RegularMesh, meshes, n_meshes, mesh_dict + use hdf5_interface + use particle_header, only: Particle + use string, only: to_str + use tally_filter_header + use xml_interface + + implicit none + private + public :: openmc_meshsurface_filter_set_mesh + +!=============================================================================== +! MESHFILTER indexes the location of particle events to a regular mesh. For +! tracklength tallies, it will produce multiple valid bins and the bin weight +! will correspond to the fraction of the track length that lies in that bin. +!=============================================================================== + + type, public, extends(TallyFilter) :: MeshSurfaceFilter + integer :: mesh + contains + procedure :: from_xml + procedure :: get_all_bins + procedure :: to_statepoint + procedure :: text_label + end type MeshSurfaceFilter + +contains + + subroutine from_xml(this, node) + class(MeshSurfaceFilter), intent(inout) :: this + type(XMLNode), intent(in) :: node + + integer :: i_mesh + integer :: id + integer :: n + integer :: n_dim + integer :: val + + n = node_word_count(node, "bins") + + if (n /= 1) call fatal_error("Only one mesh can be & + &specified per mesh filter.") + + ! Determine id of mesh + call get_node_value(node, "bins", id) + + ! Get pointer to mesh + val = mesh_dict % get(id) + if (val /= EMPTY) then + i_mesh = val + else + call fatal_error("Could not find mesh " // trim(to_str(id)) & + // " specified on filter.") + end if + + ! Determine number of bins + n_dim = meshes(i_mesh) % n_dimension + this % n_bins = 4*n_dim*product(meshes(i_mesh) % dimension + 1) + + ! Store the index of the mesh + this % mesh = i_mesh + end subroutine from_xml + + subroutine get_all_bins(this, p, estimator, match) + class(MeshSurfaceFilter), intent(in) :: this + type(Particle), intent(in) :: p + integer, intent(in) :: estimator + type(TallyFilterMatch), intent(inout) :: match + + integer :: j ! loop indices + integer :: n_dim ! num dimensions of the mesh + integer :: d1 ! dimension index + integer :: d2 ! dimension index + integer :: d3 ! dimension index + integer :: ijk0(3) ! indices of starting coordinates + integer :: ijk1(3) ! indices of ending coordinates + integer :: n_cross ! number of surface crossings + integer :: i_mesh ! flattened mesh bin index + integer :: i_surf ! surface index (1--12) + integer :: i_bin ! actual index for filter + real(8) :: uvw(3) ! cosine of angle of particle + real(8) :: xyz0(3) ! starting/intermediate coordinates + real(8) :: xyz1(3) ! ending coordinates of particle + real(8) :: xyz_cross(3) ! coordinates of bounding surfaces + real(8) :: d(3) ! distance to each bounding surface + real(8) :: distance ! actual distance traveled + logical :: start_in_mesh ! particle's starting xyz in mesh? + logical :: end_in_mesh ! particle's ending xyz in mesh? + logical :: cross_surface ! whether the particle crosses a surface + + ! Copy starting and ending location of particle + xyz0 = p % last_xyz_current + xyz1 = p % coord(1) % xyz + + associate (m => meshes(this % mesh)) + n_dim = m % n_dimension + + ! Determine indices for starting and ending location + call m % get_indices(xyz0, ijk0, start_in_mesh) + call m % get_indices(xyz1, ijk1, end_in_mesh) + + ! Check to see if start or end is in mesh -- if not, check if track still + ! intersects with mesh + if ((.not. start_in_mesh) .and. (.not. end_in_mesh)) then + if (.not. m % intersects(xyz0, xyz1)) return + end if + + ! Calculate number of surface crossings + n_cross = sum(abs(ijk1(:n_dim) - ijk0(:n_dim))) + if (n_cross == 0) return + + ! Copy particle's direction + uvw = p % coord(1) % uvw + + ! Bounding coordinates + do d1 = 1, n_dim + if (uvw(d1) > 0) then + xyz_cross(d1) = m % lower_left(d1) + ijk0(d1) * m % width(d1) + else + xyz_cross(d1) = m % lower_left(d1) + (ijk0(d1) - 1) * m % width(d1) + end if + end do + + do j = 1, n_cross + ! Set the distances to infinity + d = INFINITY + + ! Calculate distance to each bounding surface. We need to treat + ! special case where the cosine of the angle is zero since this would + ! result in a divide-by-zero. + do d1 = 1, n_dim + if (uvw(d1) == 0) then + d(d1) = INFINITY + else + d(d1) = (xyz_cross(d1) - xyz0(d1))/uvw(d1) + end if + end do + + ! Determine the closest bounding surface of the mesh cell by + ! calculating the minimum distance. Then use the minimum distance and + ! direction of the particle to determine which surface was crossed. + distance = minval(d) + + ! Loop over the dimensions + do d1 = 1, n_dim + + ! Get the other dimensions. + if (d1 == 1) then + d2 = mod(d1, 3) + 1 + d3 = mod(d1 + 1, 3) + 1 + else + d2 = mod(d1 + 1, 3) + 1 + d3 = mod(d1, 3) + 1 + end if + + ! Check whether distance is the shortest distance + if (distance == d(d1)) then + + ! Check whether particle is moving in positive d1 direction + if (uvw(d1) > 0) then + + ! Outward current on d1 max surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 1 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*i_mesh + i_surf + 1 + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + + ! Inward current on d1 min surface + cross_surface = .false. + select case(n_dim) + + case (1) + if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1)) then + cross_surface = .true. + end if + + case (2) + if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & + ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then + cross_surface = .true. + end if + + case (3) + if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & + ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & + ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then + cross_surface = .true. + end if + end select + + ! If the particle crossed the surface, tally the current + if (cross_surface) then + ijk0(d1) = ijk0(d1) + 1 + i_surf = d1 * 4 - 2 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*i_mesh + i_surf + 1 + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + + ijk0(d1) = ijk0(d1) - 1 + end if + + ijk0(d1) = ijk0(d1) + 1 + xyz_cross(d1) = xyz_cross(d1) + m % width(d1) + + ! The particle is moving in the negative d1 direction + else + + ! Outward current on d1 min surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 3 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*i_mesh + i_surf + 1 + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + + ! Inward current on d1 max surface + cross_surface = .false. + select case(n_dim) + + case (1) + if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1) then + cross_surface = .true. + end if + + case (2) + if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& + ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then + cross_surface = .true. + end if + + case (3) + if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& + ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & + ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then + cross_surface = .true. + end if + end select + + ! If the particle crossed the surface, tally the current + if (cross_surface) then + ijk0(d1) = ijk0(d1) - 1 + i_surf = d1 * 4 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*i_mesh + i_surf + 1 + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + + ijk0(d1) = ijk0(d1) + 1 + end if + + ijk0(d1) = ijk0(d1) - 1 + xyz_cross(d1) = xyz_cross(d1) - m % width(d1) + end if + end if + end do + + ! Calculate new coordinates + xyz0 = xyz0 + distance * uvw + end do + end associate + + end subroutine get_all_bins + + subroutine to_statepoint(this, filter_group) + class(MeshSurfaceFilter), intent(in) :: this + integer(HID_T), intent(in) :: filter_group + + call write_dataset(filter_group, "type", "meshsurface") + call write_dataset(filter_group, "n_bins", this % n_bins) + call write_dataset(filter_group, "bins", meshes(this % mesh) % id) + end subroutine to_statepoint + + function text_label(this, bin) result(label) + class(MeshSurfaceFilter), intent(in) :: this + integer, intent(in) :: bin + character(MAX_LINE_LEN) :: label + + integer :: i_mesh + integer :: i_surf + integer :: n_dim + integer, allocatable :: ijk(:) + + associate (m => meshes(this % mesh)) + n_dim = m % n_dimension + allocate(ijk(n_dim)) + + ! Get flattend mesh index and surface index + i_mesh = (bin - 1) / (4*n_dim) + i_surf = mod(bin - 1, 4*n_dim) + 1 + + ! Get mesh index part of label + call m % get_indices_from_bin(i_mesh, ijk) + if (m % n_dimension == 1) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ")" + elseif (m % n_dimension == 2) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ", " // & + trim(to_str(ijk(2))) // ")" + elseif (m % n_dimension == 3) then + label = "Mesh Index (" // trim(to_str(ijk(1))) // ", " // & + trim(to_str(ijk(2))) // ", " // trim(to_str(ijk(3))) // ")" + end if + + ! Get surface part of label + select case (i_surf) + case (OUT_LEFT) + label = trim(label) // " Outgoing, x-min" + case (IN_LEFT) + label = trim(label) // " Incoming, x-min" + case (OUT_RIGHT) + label = trim(label) // " Outgoing, x-max" + case (IN_RIGHT) + label = trim(label) // " Incoming, x-max" + case (OUT_BACK) + label = trim(label) // " Outgoing, y-min" + case (IN_BACK) + label = trim(label) // " Incoming, y-min" + case (OUT_FRONT) + label = trim(label) // " Outgoing, y-max" + case (IN_FRONT) + label = trim(label) // " Incoming, y-max" + case (OUT_BOTTOM) + label = trim(label) // " Outgoing, z-min" + case (IN_BOTTOM) + label = trim(label) // " Incoming, z-min" + case (OUT_TOP) + label = trim(label) // " Outgoing, z-max" + case (IN_TOP) + label = trim(label) // " Incoming, z-max" + end select + end associate + end function text_label + +!=============================================================================== +! C API FUNCTIONS +!=============================================================================== + + function openmc_meshsurface_filter_set_mesh(index, index_mesh) result(err) bind(C) + ! Set the mesh for a mesh filter + integer(C_INT32_T), value, intent(in) :: index + integer(C_INT32_T), value, intent(in) :: index_mesh + integer(C_INT) :: err + + integer :: n_dim + + err = 0 + if (index >= 1 .and. index <= n_filters) then + if (allocated(filters(index) % obj)) then + select type (f => filters(index) % obj) + type is (MeshSurfaceFilter) + if (index_mesh >= 1 .and. index_mesh <= n_meshes) then + f % mesh = index_mesh + n_dim = meshes(index_mesh) % n_dimension + f % n_bins = 4*n_dim*product(meshes(index_mesh) % dimension + 1) + else + err = E_OUT_OF_BOUNDS + call set_errmsg("Index in 'meshes' array is out of bounds.") + end if + class default + err = E_INVALID_TYPE + call set_errmsg("Tried to set mesh on a non-mesh filter.") + end select + else + err = E_ALLOCATE + call set_errmsg("Filter type has not been set yet.") + end if + else + err = E_OUT_OF_BOUNDS + call set_errmsg("Index in filters array out of bounds.") + end if + end function openmc_meshsurface_filter_set_mesh + +end module tally_filter_meshsurface diff --git a/src/tallies/tally_header.F90 b/src/tallies/tally_header.F90 index 9604d2382a..6266005c2c 100644 --- a/src/tallies/tally_header.F90 +++ b/src/tallies/tally_header.F90 @@ -336,6 +336,8 @@ contains j = FILTER_SURFACE type is (MeshFilter) j = FILTER_MESH + type is (MeshSurfaceFilter) + j = FILTER_MESHSURFACE type is (EnergyFilter) j = FILTER_ENERGYIN type is (EnergyoutFilter) From 616d492d01aaeb6b5232408cbb58e40dbb1d04ce Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Mar 2018 15:52:57 -0500 Subject: [PATCH 206/212] Don't include 0-index mesh cells for mesh surface filter --- src/input_xml.F90 | 1 + src/output.F90 | 6 - src/tallies/tally.F90 | 350 +++++++---------------- src/tallies/tally_filter_meshsurface.F90 | 122 +++----- 4 files changed, 130 insertions(+), 349 deletions(-) diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 792450e517..39369287ea 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -2927,6 +2927,7 @@ contains err = openmc_tally_set_filters(i_start + i - 1, n_filter, temp_filter) deallocate(temp_filter) else + t % type = TALLY_MESH_CURRENT t % score_bins(j) = SCORE_CURRENT end if diff --git a/src/output.F90 b/src/output.F90 index 964289126c..ecfaa94d5c 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -771,12 +771,6 @@ contains end associate end if - ! Handle surface current tallies separately - if (t % type == TALLY_MESH_CURRENT) then - call write_surface_current(t, unit_tally) - cycle - end if - ! WARNING: Admittedly, the logic for moving for printing results is ! extremely confusing and took quite a bit of time to get correct. The ! logic is structured this way since it is not practical to have a do diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index a9a5fd8bfc..d112961397 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -3064,7 +3064,7 @@ contains ! tally total or partial currents between two cells !=============================================================================== - subroutine score_surface_tally(p) + subroutine score_surface_tally(p) type(Particle), intent(in) :: p @@ -3199,277 +3199,121 @@ contains integer :: i integer :: i_tally - integer :: j, k ! loop indices - integer :: n_dim ! num dimensions of the mesh - integer :: d1 ! dimension index - integer :: d2 ! dimension index - integer :: d3 ! dimension index - integer :: ijk0(3) ! indices of starting coordinates - integer :: ijk1(3) ! indices of ending coordinates - integer :: n_cross ! number of surface crossings - integer :: filter_index ! index of scoring bin - integer :: i_filter_mesh ! index of mesh filter in filters array - integer :: i_filter_surf ! index of surface filter in filters - integer :: i_filter_energy ! index of energy filter in filters - real(8) :: uvw(3) ! cosine of angle of particle - real(8) :: xyz0(3) ! starting/intermediate coordinates - real(8) :: xyz1(3) ! ending coordinates of particle - real(8) :: xyz_cross(3) ! coordinates of bounding surfaces - real(8) :: d(3) ! distance to each bounding surface - real(8) :: distance ! actual distance traveled - integer :: matching_bin ! next valid filter bin - logical :: start_in_mesh ! particle's starting xyz in mesh? - logical :: end_in_mesh ! particle's ending xyz in mesh? - logical :: cross_surface ! whether the particle crosses a surface - logical :: energy_filter ! energy filter present - type(RegularMesh), pointer :: m + integer :: i_filt + integer :: i_bin + integer :: q ! loop index for scoring bins + integer :: k ! working index for expand and score + integer :: score_bin ! scoring bin, e.g. SCORE_FLUX + integer :: score_index ! scoring bin index + integer :: j ! loop index for scoring bins + integer :: filter_index ! single index for single bin + real(8) :: flux ! collision estimate of flux + real(8) :: filter_weight ! combined weight of all filters + real(8) :: score ! analog tally score + logical :: finished ! found all valid bin combinations + + ! No collision, so no weight change when survival biasing + flux = p % wgt TALLY_LOOP: do i = 1, active_current_tallies % size() - ! Copy starting and ending location of particle - xyz0 = p % last_xyz_current - xyz1 = p % coord(1) % xyz - - ! Get pointer to tally + ! Get index of tally and pointer to tally i_tally = active_current_tallies % data(i) associate (t => tallies(i_tally) % obj) - ! Check for energy filter - energy_filter = (t % find_filter(FILTER_ENERGYIN) > 0) - - ! Get index for mesh, surface, and energy filters - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - if (energy_filter) then - i_filter_energy = t % filter(t % find_filter(FILTER_ENERGYIN)) - end if - - ! Reset the matching bins arrays - call filter_matches(i_filter_mesh) % bins % resize(1) - call filter_matches(i_filter_surf) % bins % resize(1) - if (energy_filter) then - call filter_matches(i_filter_energy) % bins % resize(1) - end if - - ! Get pointer to mesh - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - n_dim = m % n_dimension - - ! Determine indices for starting and ending location - call m % get_indices(xyz0, ijk0, start_in_mesh) - call m % get_indices(xyz1, ijk1, end_in_mesh) - - ! Check to see if start or end is in mesh -- if not, check if track still - ! intersects with mesh - if ((.not. start_in_mesh) .and. (.not. end_in_mesh)) then - if (.not. m % intersects(xyz0, xyz1)) cycle - end if - - ! Calculate number of surface crossings - n_cross = sum(abs(ijk1(:n_dim) - ijk0(:n_dim))) - if (n_cross == 0) then - cycle - end if - - ! Copy particle's direction - uvw = p % coord(1) % uvw - - ! Determine incoming energy bin. We need to tell the energy filter this - ! is a tracklength tally so it uses the pre-collision energy. - if (energy_filter) then - call filter_matches(i_filter_energy) % bins % clear() - call filter_matches(i_filter_energy) % weights % clear() - call filters(i_filter_energy) % obj % get_all_bins(p, & - ESTIMATOR_TRACKLENGTH, filter_matches(i_filter_energy)) - if (filter_matches(i_filter_energy) % bins % size() == 0) cycle - matching_bin = filter_matches(i_filter_energy) % bins % data(1) - filter_matches(i_filter_energy) % bins % data(1) = matching_bin - end if - - ! Bounding coordinates - do d1 = 1, n_dim - if (uvw(d1) > 0) then - xyz_cross(d1) = m % lower_left(d1) + ijk0(d1) * m % width(d1) - else - xyz_cross(d1) = m % lower_left(d1) + (ijk0(d1) - 1) * m % width(d1) + ! Find all valid bins in each filter if they have not already been found + ! for a previous tally. + do j = 1, size(t % filter) + i_filt = t % filter(j) + if (.not. filter_matches(i_filt) % bins_present) then + call filter_matches(i_filt) % bins % clear() + call filter_matches(i_filt) % weights % clear() + call filters(i_filt) % obj % get_all_bins(p, t % estimator, & + filter_matches(i_filt)) + filter_matches(i_filt) % bins_present = .true. end if + ! If there are no valid bins for this filter, then there is nothing to + ! score and we can move on to the next tally. + if (filter_matches(i_filt) % bins % size() == 0) cycle TALLY_LOOP + + ! Set the index of the bin used in the first filter combination + filter_matches(i_filt) % i_bin = 1 end do - do j = 1, n_cross - ! Reset scoring bin index - filter_matches(i_filter_surf) % bins % data(1) = 0 + ! ======================================================================== + ! Loop until we've covered all valid bins on each of the filters. - ! Set the distances to infinity - d = INFINITY + FILTER_LOOP: do - ! Calculate distance to each bounding surface. We need to treat - ! special case where the cosine of the angle is zero since this would - ! result in a divide-by-zero. - do d1 = 1, n_dim - if (uvw(d1) == 0) then - d(d1) = INFINITY + ! Reset scoring index and weight + filter_index = 1 + filter_weight = ONE + + ! Determine scoring index and weight for this filter combination + do j = 1, size(t % filter) + i_filt = t % filter(j) + i_bin = filter_matches(i_filt) % i_bin + filter_index = filter_index + (filter_matches(i_filt) % bins % & + data(i_bin) - 1) * t % stride(j) + filter_weight = filter_weight * filter_matches(i_filt) % weights % & + data(i_bin) + end do + + ! Determine score + score = flux * filter_weight + + ! Currently only one score type + k = 0 + SCORE_LOOP: do q = 1, t % n_user_score_bins + k = k + 1 + + ! determine what type of score bin + score_bin = t % score_bins(q) + + ! determine scoring bin index, no offset from nuclide bins + score_index = q + + call expand_and_score(p, t, score_index, filter_index, score_bin, & + score, k) + end do SCORE_LOOP + + ! ====================================================================== + ! Filter logic + + ! Increment the filter bins, starting with the last filter to find the + ! next valid bin combination + finished = .true. + do j = size(t % filter), 1, -1 + i_filt = t % filter(j) + if (filter_matches(i_filt) % i_bin < filter_matches(i_filt) % & + bins % size()) then + filter_matches(i_filt) % i_bin = filter_matches(i_filt) % i_bin + 1 + finished = .false. + exit else - d(d1) = (xyz_cross(d1) - xyz0(d1))/uvw(d1) + filter_matches(i_filt) % i_bin = 1 end if end do - ! Determine the closest bounding surface of the mesh cell by - ! calculating the minimum distance. Then use the minimum distance and - ! direction of the particle to determine which surface was crossed. - distance = minval(d) + ! Once we have finished all valid bins for each of the filters, exit + ! the loop. + if (finished) exit FILTER_LOOP - ! Loop over the dimensions - do d1 = 1, n_dim - - ! Get the other dimensions. - if (d1 == 1) then - d2 = mod(d1, 3) + 1 - d3 = mod(d1 + 1, 3) + 1 - else - d2 = mod(d1 + 1, 3) + 1 - d3 = mod(d1, 3) + 1 - end if - - ! Check whether distance is the shortest distance - if (distance == d(d1)) then - - ! Check whether particle is moving in positive d1 direction - if (uvw(d1) > 0) then - - ! Outward current on d1 max surface - if (all(ijk0(:n_dim) >= 1) .and. & - all(ijk0(:n_dim) <= m % dimension)) then - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 1 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - end if - - ! Inward current on d1 min surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1)) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) + 1 - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 2 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - ijk0(d1) = ijk0(d1) - 1 - end if - - ijk0(d1) = ijk0(d1) + 1 - xyz_cross(d1) = xyz_cross(d1) + m % width(d1) - - ! The particle is moving in the negative d1 direction - else - - ! Outward current on d1 min surface - if (all(ijk0(:n_dim) >= 1) .and. & - all(ijk0(:n_dim) <= m % dimension)) then - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - 3 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - end if - - ! Inward current on d1 max surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) - 1 - filter_matches(i_filter_surf) % bins % data(1) = d1 * 4 - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices(ijk0) - filter_index = 1 - do k = 1, size(t % filter) - filter_index = filter_index + (filter_matches(t % & - filter(k)) % bins % data(1) - 1) * t % stride(k) - end do -!$omp atomic - t % results(RESULT_VALUE, 1, filter_index) = & - t % results(RESULT_VALUE, 1, filter_index) + p % wgt - ijk0(d1) = ijk0(d1) + 1 - end if - - ijk0(d1) = ijk0(d1) - 1 - xyz_cross(d1) = xyz_cross(d1) - m % width(d1) - end if - end if - end do - - ! Calculate new coordinates - xyz0 = xyz0 + distance * uvw - end do + end do FILTER_LOOP end associate + + ! If the user has specified that we can assume all tallies are spatially + ! separate, this implies that once a tally has been scored to, we needn't + ! check the others. This cuts down on overhead when there are many + ! tallies specified + + if (assume_separate) exit TALLY_LOOP + end do TALLY_LOOP + ! Reset filter matches flag + filter_matches(:) % bins_present = .false. + end subroutine score_surface_current !=============================================================================== diff --git a/src/tallies/tally_filter_meshsurface.F90 b/src/tallies/tally_filter_meshsurface.F90 index e45261f440..1913c8b0de 100644 --- a/src/tallies/tally_filter_meshsurface.F90 +++ b/src/tallies/tally_filter_meshsurface.F90 @@ -64,7 +64,7 @@ contains ! Determine number of bins n_dim = meshes(i_mesh) % n_dimension - this % n_bins = 4*n_dim*product(meshes(i_mesh) % dimension + 1) + this % n_bins = 4*n_dim*product(meshes(i_mesh) % dimension) ! Store the index of the mesh this % mesh = i_mesh @@ -79,8 +79,6 @@ contains integer :: j ! loop indices integer :: n_dim ! num dimensions of the mesh integer :: d1 ! dimension index - integer :: d2 ! dimension index - integer :: d3 ! dimension index integer :: ijk0(3) ! indices of starting coordinates integer :: ijk1(3) ! indices of ending coordinates integer :: n_cross ! number of surface crossings @@ -95,7 +93,6 @@ contains real(8) :: distance ! actual distance traveled logical :: start_in_mesh ! particle's starting xyz in mesh? logical :: end_in_mesh ! particle's ending xyz in mesh? - logical :: cross_surface ! whether the particle crosses a surface ! Copy starting and ending location of particle xyz0 = p % last_xyz_current @@ -153,15 +150,6 @@ contains ! Loop over the dimensions do d1 = 1, n_dim - ! Get the other dimensions. - if (d1 == 1) then - d2 = mod(d1, 3) + 1 - d3 = mod(d1 + 1, 3) + 1 - else - d2 = mod(d1 + 1, 3) + 1 - d3 = mod(d1, 3) + 1 - end if - ! Check whether distance is the shortest distance if (distance == d(d1)) then @@ -173,103 +161,57 @@ contains all(ijk0(:n_dim) <= m % dimension)) then i_surf = d1 * 4 - 1 i_mesh = m % get_bin_from_indices(ijk0) - i_bin = 4*n_dim*i_mesh + i_surf + 1 + i_bin = 4*n_dim*(i_mesh - 1) + i_surf call match % bins % push_back(i_bin) call match % weights % push_back(ONE) end if - ! Inward current on d1 min surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1)) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) >= 0 .and. ijk0(d1) < m % dimension(d1) .and. & - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) + 1 - i_surf = d1 * 4 - 2 - i_mesh = m % get_bin_from_indices(ijk0) - i_bin = 4*n_dim*i_mesh + i_surf + 1 - - call match % bins % push_back(i_bin) - call match % weights % push_back(ONE) - - ijk0(d1) = ijk0(d1) - 1 - end if - + ! Advance position ijk0(d1) = ijk0(d1) + 1 xyz_cross(d1) = xyz_cross(d1) + m % width(d1) - ! The particle is moving in the negative d1 direction + ! If the particle crossed the surface, tally the inward current on + ! d1 min surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 - 2 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if + else + ! The particle is moving in the negative d1 direction ! Outward current on d1 min surface if (all(ijk0(:n_dim) >= 1) .and. & all(ijk0(:n_dim) <= m % dimension)) then i_surf = d1 * 4 - 3 i_mesh = m % get_bin_from_indices(ijk0) - i_bin = 4*n_dim*i_mesh + i_surf + 1 + i_bin = 4*n_dim*(i_mesh - 1) + i_surf call match % bins % push_back(i_bin) call match % weights % push_back(ONE) end if - ! Inward current on d1 max surface - cross_surface = .false. - select case(n_dim) - - case (1) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1) then - cross_surface = .true. - end if - - case (2) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2)) then - cross_surface = .true. - end if - - case (3) - if (ijk0(d1) > 1 .and. ijk0(d1) <= m % dimension(d1) + 1 .and.& - ijk0(d2) >= 1 .and. ijk0(d2) <= m % dimension(d2) .and. & - ijk0(d3) >= 1 .and. ijk0(d3) <= m % dimension(d3)) then - cross_surface = .true. - end if - end select - - ! If the particle crossed the surface, tally the current - if (cross_surface) then - ijk0(d1) = ijk0(d1) - 1 - i_surf = d1 * 4 - i_mesh = m % get_bin_from_indices(ijk0) - i_bin = 4*n_dim*i_mesh + i_surf + 1 - - call match % bins % push_back(i_bin) - call match % weights % push_back(ONE) - - ijk0(d1) = ijk0(d1) + 1 - end if - + ! Advance position ijk0(d1) = ijk0(d1) - 1 xyz_cross(d1) = xyz_cross(d1) - m % width(d1) + + ! If the particle crossed the surface, tally the inward current on + ! d1 max surface + if (all(ijk0(:n_dim) >= 1) .and. & + all(ijk0(:n_dim) <= m % dimension)) then + i_surf = d1 * 4 + i_mesh = m % get_bin_from_indices(ijk0) + i_bin = 4*n_dim*(i_mesh - 1) + i_surf + + call match % bins % push_back(i_bin) + call match % weights % push_back(ONE) + end if end if end if end do @@ -305,7 +247,7 @@ contains allocate(ijk(n_dim)) ! Get flattend mesh index and surface index - i_mesh = (bin - 1) / (4*n_dim) + i_mesh = (bin - 1) / (4*n_dim) + 1 i_surf = mod(bin - 1, 4*n_dim) + 1 ! Get mesh index part of label @@ -370,7 +312,7 @@ contains if (index_mesh >= 1 .and. index_mesh <= n_meshes) then f % mesh = index_mesh n_dim = meshes(index_mesh) % n_dimension - f % n_bins = 4*n_dim*product(meshes(index_mesh) % dimension + 1) + f % n_bins = 4*n_dim*product(meshes(index_mesh) % dimension) else err = E_OUT_OF_BOUNDS call set_errmsg("Index in 'meshes' array is out of bounds.") From c51091a1d7ee8f9ce24650a5d5975e2199f29cd0 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Mar 2018 22:08:44 -0500 Subject: [PATCH 207/212] Use new MeshSurfaceFilter for CMFD (tests pass) --- include/openmc.h | 1 + openmc/filter.py | 4 + src/api.F90 | 1 + src/cmfd_data.F90 | 65 +- src/cmfd_input.F90 | 45 +- src/constants.F90 | 2 +- src/input_xml.F90 | 86 +- src/output.F90 | 182 ---- src/tallies/tally.F90 | 2 +- src/tallies/trigger.F90 | 2 +- .../cmfd_feed/results_true.dat | 816 ------------------ .../cmfd_nofeed/results_true.dat | 816 ------------------ 12 files changed, 51 insertions(+), 1971 deletions(-) diff --git a/include/openmc.h b/include/openmc.h index bb04907a52..10c0b2de8e 100644 --- a/include/openmc.h +++ b/include/openmc.h @@ -52,6 +52,7 @@ extern "C" { int openmc_material_filter_get_bins(int32_t index, int32_t** bins, int32_t* n); int openmc_material_filter_set_bins(int32_t index, int32_t n, const int32_t* bins); int openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh); + int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh); int openmc_next_batch(); int openmc_nuclide_name(int index, char** name); void openmc_plot_geometry(); diff --git a/openmc/filter.py b/openmc/filter.py index 26629dafe0..d7b8267e96 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -845,6 +845,10 @@ class MeshFilter(Filter): return df +class MeshSurfaceFilter(MeshFilter): + pass + + class RealFilter(Filter): """Tally modifier that describes phase-space and other characteristics diff --git a/src/api.F90 b/src/api.F90 index d79a32d945..64324da3b1 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -75,6 +75,7 @@ module openmc_api public :: openmc_material_filter_get_bins public :: openmc_material_filter_set_bins public :: openmc_mesh_filter_set_mesh + public :: openmc_meshsurface_filter_set_mesh public :: openmc_next_batch public :: openmc_nuclide_name public :: openmc_plot_geometry diff --git a/src/cmfd_data.F90 b/src/cmfd_data.F90 index 521be5e3f2..3152f1eb2b 100644 --- a/src/cmfd_data.F90 +++ b/src/cmfd_data.F90 @@ -73,12 +73,10 @@ contains integer :: ital ! tally object index integer :: ijk(3) ! indices for mesh cell integer :: score_index ! index to pull from tally object - integer :: i_filt ! index in filters array integer :: i_filter_mesh ! index for mesh filter integer :: i_filter_ein ! index for incoming energy filter integer :: i_filter_eout ! index for outgoing energy filter - integer :: i_filter_surf ! index for surface filter - integer :: stride_surf ! stride for surface filter + integer :: i_mesh ! flattend index for mesh logical :: energy_filters! energy filters present real(8) :: flux ! temp variable for flux type(RegularMesh), pointer :: m ! pointer for mesh object @@ -95,10 +93,10 @@ contains ! Associate tallies and mesh associate (t => cmfd_tallies(1) % obj) - i_filt = t % filter(t % find_filter(FILTER_MESH)) + i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) end associate - select type(filt => filters(i_filt) % obj) + select type(filt => filters(i_filter_mesh) % obj) type is (MeshFilter) m => meshes(filt % mesh) end select @@ -115,16 +113,16 @@ contains ! Associate tallies and mesh associate (t => cmfd_tallies(ital) % obj) - i_filt = t % filter(t % find_filter(FILTER_MESH)) - select type(filt => filters(i_filt) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select + + if (ital < 3) then + i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) + else + i_filter_mesh = t % filter(t % find_filter(FILTER_MESHSURFACE)) + end if ! Check for energy filters energy_filters = (t % find_filter(FILTER_ENERGYIN) > 0) - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) if (energy_filters) then i_filter_ein = t % filter(t % find_filter(FILTER_ENERGYIN)) i_filter_eout = t % filter(t % find_filter(FILTER_ENERGYOUT)) @@ -247,65 +245,62 @@ contains else if (ital == 3) then - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - stride_surf = t % stride(t % find_filter(FILTER_SURFACE)) - ! Initialize and filter for energy do l = 1, size(t % filter) call filter_matches(t % filter(l)) % bins % clear() call filter_matches(t % filter(l)) % bins % push_back(1) end do + + ! Set the bin for this mesh cell + i_mesh = m % get_bin_from_indices([ i, j, k ]) + filter_matches(i_filter_mesh) % bins % data(1) = 12*(i_mesh - 1) + 1 + + ! Set the energy bin if needed if (energy_filters) then filter_matches(i_filter_ein) % bins % data(1) = ng - h + 1 end if - ! Get the bin for this mesh cell - filter_matches(i_filter_mesh) % bins % data(1) = & - m % get_bin_from_indices([ i, j, k ]) - - score_index = 1 + score_index = 0 do l = 1, size(t % filter) - if (t % filter(l) == i_filter_surf) cycle score_index = score_index + (filter_matches(t % filter(l)) & % bins % data(1) - 1) * t % stride(l) end do ! Left surface cmfd % current(1,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_LEFT - 1) * stride_surf) + score_index + OUT_LEFT) cmfd % current(2,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_LEFT - 1) * stride_surf) + score_index + IN_LEFT) ! Right surface cmfd % current(3,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_RIGHT - 1) * stride_surf) + score_index + IN_RIGHT) cmfd % current(4,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_RIGHT - 1) * stride_surf) + score_index + OUT_RIGHT) ! Back surface cmfd % current(5,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_BACK - 1) * stride_surf) + score_index + OUT_BACK) cmfd % current(6,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_BACK - 1) * stride_surf) + score_index + IN_BACK) ! Front surface cmfd % current(7,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_FRONT - 1) * stride_surf) + score_index + IN_FRONT) cmfd % current(8,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_FRONT - 1) * stride_surf) + score_index + OUT_FRONT) - ! Bottom surface + ! Left surface cmfd % current(9,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_BOTTOM - 1) * stride_surf) + score_index + OUT_BOTTOM) cmfd % current(10,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_BOTTOM - 1) * stride_surf) + score_index + IN_BOTTOM) - ! Top surface + ! Right surface cmfd % current(11,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (IN_TOP - 1) * stride_surf) + score_index + IN_TOP) cmfd % current(12,h,i,j,k) = t % results(RESULT_SUM, 1, & - score_index + (OUT_TOP - 1) * stride_surf) - + score_index + OUT_TOP) end if TALLY end do OUTGROUP diff --git a/src/cmfd_input.F90 b/src/cmfd_input.F90 index dbfabb2540..86f4e2400e 100644 --- a/src/cmfd_input.F90 +++ b/src/cmfd_input.F90 @@ -373,7 +373,7 @@ contains ! Determine number of filters energy_filters = check_for_node(node_mesh, "energy") - n = merge(5, 3, energy_filters) + n = merge(4, 2, energy_filters) ! Extend filters array so we can add CMFD filters err = openmc_extend_filters(n, i_filt_start, i_filt_end) @@ -409,44 +409,15 @@ contains ! Duplicate the mesh filter for the mesh current tally since other ! tallies use this filter and we need to change the dimension i_filt = i_filt + 1 - err = openmc_filter_set_type(i_filt, C_CHAR_'mesh' // C_NULL_CHAR) + err = openmc_filter_set_type(i_filt, C_CHAR_'meshsurface' // C_NULL_CHAR) call openmc_get_filter_next_id(filt_id) err = openmc_filter_set_id(i_filt, filt_id) - err = openmc_mesh_filter_set_mesh(i_filt, i_start) + err = openmc_meshsurface_filter_set_mesh(i_filt, i_start) - ! We need to increase the dimension by one since we also need - ! currents coming into and out of the boundary mesh cells. - filters(i_filt) % obj % n_bins = product(m % dimension + 1) - - ! Set up surface filter - i_filt = i_filt + 1 - allocate(SurfaceFilter :: filters(i_filt) % obj) - select type(filt => filters(i_filt) % obj) - type is(SurfaceFilter) - filt % id = i_filt - filt % n_bins = 4 * m % n_dimension - allocate(filt % surfaces(4 * m % n_dimension)) - if (m % n_dimension == 2) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, IN_RIGHT, OUT_RIGHT, & - OUT_BACK, IN_BACK, IN_FRONT, OUT_FRONT /) - elseif (m % n_dimension == 3) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, IN_RIGHT, OUT_RIGHT, & - OUT_BACK, IN_BACK, IN_FRONT, OUT_FRONT, & - OUT_BOTTOM, IN_BOTTOM, IN_TOP, OUT_TOP /) - end if - filt % current = .true. - ! Add filter to dictionary - call filter_dict % set(filt % id, i_filt) - end select ! Initialize filters do i = i_filt_start, i_filt_end - select type (filt => filters(i) % obj) - type is (SurfaceFilter) - ! Don't do anything - class default - call filt % initialize() - end select + call filters(i) % obj % initialize() end do ! Allocate tallies @@ -564,13 +535,9 @@ contains ! Set tally estimator to analog t % estimator = ESTIMATOR_ANALOG - ! Set the surface filter index in the tally find_filter array - n_filter = n_filter + 1 - ! Allocate and set filters allocate(filter_indices(n_filter)) - filter_indices(1) = i_filt_end - 1 - filter_indices(n_filter) = i_filt_end + filter_indices(1) = i_filt_end if (energy_filters) then filter_indices(2) = i_filt_start + 1 end if @@ -588,7 +555,7 @@ contains ! Set macro bins t % score_bins(1) = SCORE_CURRENT - t % type = TALLY_MESH_CURRENT + t % type = TALLY_MESH_SURFACE end if ! Make CMFD tallies active from the start diff --git a/src/constants.F90 b/src/constants.F90 index 75a9471490..0e138f0ee5 100644 --- a/src/constants.F90 +++ b/src/constants.F90 @@ -292,7 +292,7 @@ module constants ! Tally type integer, parameter :: & TALLY_VOLUME = 1, & - TALLY_MESH_CURRENT = 2, & + TALLY_MESH_SURFACE = 2, & TALLY_SURFACE = 3 ! Tally estimator types diff --git a/src/input_xml.F90 b/src/input_xml.F90 index 39369287ea..a0b077a940 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -2197,7 +2197,6 @@ contains integer :: l ! another loop index integer :: filter_id ! user-specified identifier for filter integer :: i_filt ! index in filters array - integer :: i_filter_mesh ! index of mesh filter integer :: i_elem ! index of entry in dictionary integer :: n ! size of arrays in mesh specification integer :: n_words ! number of words read @@ -2209,7 +2208,6 @@ contains integer :: trig_ind ! index of triggers array for each tally integer :: user_trig_ind ! index of user-specified triggers for each tally integer :: i_start, i_end - integer :: i_filt_start, i_filt_end integer(C_INT) :: err real(8) :: threshold ! trigger convergence threshold integer :: n_order ! moment order requested @@ -2838,18 +2836,18 @@ contains &t % find_filter(FILTER_CELL) > 0 .or. & &t % find_filter(FILTER_CELLFROM) > 0) then - ! Check to make sure that mesh currents are not desired as well - if (t % find_filter(FILTER_MESH) > 0) then - call fatal_error("Cannot tally other mesh currents & - &in the same tally as surface currents") + ! Check to make sure that mesh surface currents are not desired as well + if (t % find_filter(FILTER_MESHSURFACE) > 0) then + call fatal_error("Cannot tally mesh surface currents & + &in the same tally as normal surface currents") end if t % type = TALLY_SURFACE t % score_bins(j) = SCORE_CURRENT - else if (t % find_filter(FILTER_MESH) > 0) then + else if (t % find_filter(FILTER_MESHSURFACE) > 0) then t % score_bins(j) = SCORE_CURRENT - t % type = TALLY_MESH_CURRENT + t % type = TALLY_MESH_SURFACE ! Check to make sure that current is the only desired response ! for this tally @@ -2857,78 +2855,6 @@ contains call fatal_error("Cannot tally other scores in the & &same tally as surface currents") end if - - ! Get index of mesh filter - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - - ! Check to make sure mesh filter was specified - if (i_filter_mesh == 0) then - call fatal_error("Cannot tally surface current without a mesh & - &filter.") - end if - - ! Get pointer to mesh - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - ! Extend the filters array so we can add a surface filter and - ! mesh filter - err = openmc_extend_filters(2, i_filt_start, i_filt_end) - - ! Duplicate the mesh filter since other tallies might use this - ! filter and we need to change the dimension - filters(i_filt_start) = filters(i_filter_mesh) - - ! We need to increase the dimension by one since we also need - ! currents coming into and out of the boundary mesh cells. - filters(i_filt_start) % obj % n_bins = product(m % dimension + 1) - - ! Set ID - call openmc_get_filter_next_id(filter_id) - err = openmc_filter_set_id(i_filt_start, filter_id) - - - ! Add surface filter - allocate(SurfaceFilter :: filters(i_filt_end) % obj) - select type (filt => filters(i_filt_end) % obj) - type is (SurfaceFilter) - filt % n_bins = 4 * m % n_dimension - allocate(filt % surfaces(4 * m % n_dimension)) - if (m % n_dimension == 1) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT /) - elseif (m % n_dimension == 2) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT, & - OUT_BACK, IN_BACK, OUT_FRONT, IN_FRONT /) - elseif (m % n_dimension == 3) then - filt % surfaces = (/ OUT_LEFT, IN_LEFT, OUT_RIGHT, IN_RIGHT, & - OUT_BACK, IN_BACK, OUT_FRONT, IN_FRONT, OUT_BOTTOM, & - IN_BOTTOM, OUT_TOP, IN_TOP /) - end if - filt % current = .true. - - ! Set ID - call openmc_get_filter_next_id(filter_id) - err = openmc_filter_set_id(i_filt_end, filter_id) - end select - - ! Copy filter indices to resized array - n_filter = size(t % filter) - allocate(temp_filter(n_filter + 1)) - temp_filter(1:size(t % filter)) = t % filter - n_filter = n_filter + 1 - - ! Set mesh and surface filters - temp_filter(t % find_filter(FILTER_MESH)) = i_filt_start - temp_filter(n_filter) = i_filt_end - - ! Set filters - err = openmc_tally_set_filters(i_start + i - 1, n_filter, temp_filter) - deallocate(temp_filter) - else - t % type = TALLY_MESH_CURRENT - t % score_bins(j) = SCORE_CURRENT end if case ('events') diff --git a/src/output.F90 b/src/output.F90 index ecfaa94d5c..b6809ca82f 100644 --- a/src/output.F90 +++ b/src/output.F90 @@ -932,188 +932,6 @@ contains end subroutine write_tallies -!=============================================================================== -! WRITE_SURFACE_CURRENT writes out surface current tallies over a mesh to the -! tallies.out file. -!=============================================================================== - - subroutine write_surface_current(t, unit_tally) - type(TallyObject), intent(in) :: t - integer, intent(in) :: unit_tally - - integer :: i ! mesh index - integer :: j ! loop index over tally filters - integer :: ijk(3) ! indices of mesh cells - integer :: n_dim ! number of mesh dimensions - integer :: n_cells ! number of mesh cells - integer :: l ! index for energy - integer :: i_filter_mesh ! index for mesh filter - integer :: i_filter_ein ! index for incoming energy filter - integer :: i_filter_surf ! index for surface filter - integer :: stride_surf ! stride for surface filter - integer :: n ! number of incoming energy bins - integer :: filter_index ! index in results array for filters - integer :: nr ! number of realizations - real(8) :: x(2) ! mean and standard deviation - logical :: print_ebin ! should incoming energy bin be displayed? - logical :: energy_filters ! energy filters present - character(MAX_LINE_LEN) :: string - type(RegularMesh), pointer :: m - type(TallyFilterMatch), allocatable :: matches(:) - - allocate(matches(n_filters)) - - nr = t % n_realizations - - ! Get pointer to mesh - i_filter_mesh = t % filter(t % find_filter(FILTER_MESH)) - select type(filt => filters(i_filter_mesh) % obj) - type is (MeshFilter) - m => meshes(filt % mesh) - end select - - ! Get surface filter index and stride - i_filter_surf = t % filter(t % find_filter(FILTER_SURFACE)) - stride_surf = t % stride(t % find_filter(FILTER_SURFACE)) - - ! initialize bins array - do j = 1, size(t % filter) - call matches(t % filter(j)) % bins % clear() - call matches(t % filter(j)) % bins % push_back(1) - end do - - ! determine how many energy in bins there are - energy_filters = (t % find_filter(FILTER_ENERGYIN) > 0) - if (energy_filters) then - print_ebin = .true. - i_filter_ein = t % filter(t % find_filter(FILTER_ENERGYIN)) - n = filters(i_filter_ein) % obj % n_bins - else - print_ebin = .false. - n = 1 - end if - - ! Get the dimensions and number of cells in the mesh - n_dim = m % n_dimension - n_cells = product(m % dimension) - - ! Loop over all the mesh cells - do i = 1, n_cells - - ! Get the indices for this cell - call m % get_indices_from_bin(i, ijk) - matches(i_filter_mesh) % bins % data(1) = i - - ! Write the header for this cell - if (n_dim == 1) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ")" - else if (n_dim == 2) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ", " & - // trim(to_str(ijk(2))) // ")" - else if (n_dim == 3) then - string = "Mesh Index (" // trim(to_str(ijk(1))) // ", " & - // trim(to_str(ijk(2))) // ", " // trim(to_str(ijk(3))) // ")" - end if - - write(UNIT=unit_tally, FMT='(1X,A)') trim(string) - - do l = 1, n - if (print_ebin) then - ! Set incoming energy bin - matches(i_filter_ein) % bins % data(1) = l - - ! Write incoming energy bin - write(UNIT=unit_tally, FMT='(3X,A)') & - trim(filters(i_filter_ein) % obj % text_label( & - matches(i_filter_ein) % bins % data(1))) - end if - - filter_index = 1 - do j = 1, size(t % filter) - if (t % filter(j) == i_filter_surf) cycle - filter_index = filter_index + (matches(t % filter(j)) & - % bins % data(1) - 1) * t % stride(j) - end do - - associate(r => t % results(RESULT_SUM:RESULT_SUM_SQ, :, :)) - - ! Left Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_LEFT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Left", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_LEFT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Left", to_str(x(1)), trim(to_str(x(2))) - - ! Right Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_RIGHT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Right", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_RIGHT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Right", to_str(x(1)), trim(to_str(x(2))) - - if (n_dim >= 2) then - - ! Back Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_BACK - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Back", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_BACK - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Back", to_str(x(1)), trim(to_str(x(2))) - - ! Front Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_FRONT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Front", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_FRONT - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Front", to_str(x(1)), trim(to_str(x(2))) - end if - - if (n_dim == 3) then - - ! Bottom Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_BOTTOM - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Bottom", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_BOTTOM - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Bottom", to_str(x(1)), trim(to_str(x(2))) - - ! Top Surface - x(:) = mean_stdev(r(:, 1, filter_index + (OUT_TOP - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Outgoing Current on Top", to_str(x(1)), trim(to_str(x(2))) - - x(:) = mean_stdev(r(:, 1, filter_index + (IN_TOP - 1) * & - stride_surf), nr) - write(UNIT=unit_tally, FMT='(5X,A,T35,A,"+/- ",A)') & - "Incoming Current on Top", to_str(x(1)), trim(to_str(x(2))) - end if - end associate - end do - end do - - end subroutine write_surface_current - !=============================================================================== ! MEAN_STDEV computes the sample mean and standard deviation of the mean of a ! single tally score diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index d112961397..058c414f22 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -4236,7 +4236,7 @@ contains elseif (t % estimator == ESTIMATOR_COLLISION) then call active_collision_tallies % push_back(i) end if - elseif (t % type == TALLY_MESH_CURRENT) then + elseif (t % type == TALLY_MESH_SURFACE) then call active_current_tallies % push_back(i) elseif (t % type == TALLY_SURFACE) then call active_surface_tallies % push_back(i) diff --git a/src/tallies/trigger.F90 b/src/tallies/trigger.F90 index ee2259ed48..7dcb3d71eb 100644 --- a/src/tallies/trigger.F90 +++ b/src/tallies/trigger.F90 @@ -168,7 +168,7 @@ contains trigger % variance = ZERO ! Mesh current tally triggers require special treatment - if (t % type == TALLY_MESH_CURRENT) then + if (t % type == TALLY_MESH_SURFACE) then call compute_tally_current(t, trigger) else diff --git a/tests/regression_tests/cmfd_feed/results_true.dat b/tests/regression_tests/cmfd_feed/results_true.dat index d5eed3d3c5..5e6750fe6b 100644 --- a/tests/regression_tests/cmfd_feed/results_true.dat +++ b/tests/regression_tests/cmfd_feed/results_true.dat @@ -364,822 +364,6 @@ tally 4: 0.000000E+00 0.000000E+00 0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 cmfd indices 1.000000E+01 1.000000E+00 diff --git a/tests/regression_tests/cmfd_nofeed/results_true.dat b/tests/regression_tests/cmfd_nofeed/results_true.dat index a3fbfb9549..f00966cf8f 100644 --- a/tests/regression_tests/cmfd_nofeed/results_true.dat +++ b/tests/regression_tests/cmfd_nofeed/results_true.dat @@ -364,822 +364,6 @@ tally 4: 0.000000E+00 0.000000E+00 0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 -0.000000E+00 cmfd indices 1.000000E+01 1.000000E+00 From 206166cc41ac3de754d22584c9b03cacfc185419 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Thu, 15 Mar 2018 22:30:07 -0500 Subject: [PATCH 208/212] Remove redundant surface tally subroutine. Fix broken tests --- openmc/capi/filter.py | 8 + src/api.F90 | 3 +- src/relaxng/tallies.rnc | 16 +- src/relaxng/tallies.rng | 2 + src/tallies/tally.F90 | 142 +----------------- src/tallies/tally_header.F90 | 4 +- src/tracking.F90 | 24 +-- .../filter_mesh/inputs_true.dat | 15 +- .../filter_mesh/results_true.dat | 2 +- tests/regression_tests/filter_mesh/test.py | 9 +- .../score_current/results_true.dat | 2 +- .../score_current/tallies.xml | 2 +- 12 files changed, 63 insertions(+), 166 deletions(-) diff --git a/openmc/capi/filter.py b/openmc/capi/filter.py index 5a5df4814d..691ecc09cc 100644 --- a/openmc/capi/filter.py +++ b/openmc/capi/filter.py @@ -55,6 +55,9 @@ _dll.openmc_material_filter_set_bins.errcheck = _error_handler _dll.openmc_mesh_filter_set_mesh.argtypes = [c_int32, c_int32] _dll.openmc_mesh_filter_set_mesh.restype = c_int _dll.openmc_mesh_filter_set_mesh.errcheck = _error_handler +_dll.openmc_meshsurface_filter_set_mesh.argtypes = [c_int32, c_int32] +_dll.openmc_meshsurface_filter_set_mesh.restype = c_int +_dll.openmc_meshsurface_filter_set_mesh.errcheck = _error_handler class Filter(_FortranObjectWithID): @@ -188,6 +191,10 @@ class MeshFilter(Filter): filter_type = 'mesh' +class MeshSurfaceFilter(Filter): + filter_type = 'meshsurface' + + class MuFilter(Filter): filter_type = 'mu' @@ -216,6 +223,7 @@ _FILTER_TYPE_MAP = { 'energyfunction': EnergyFunctionFilter, 'material': MaterialFilter, 'mesh': MeshFilter, + 'meshsurface': MeshSurfaceFilter, 'mu': MuFilter, 'polar': PolarFilter, 'surface': SurfaceFilter, diff --git a/src/api.F90 b/src/api.F90 index 64324da3b1..df183c292f 100644 --- a/src/api.F90 +++ b/src/api.F90 @@ -276,8 +276,9 @@ contains ! Clear active tally lists call active_analog_tallies % clear() call active_tracklength_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() call active_collision_tallies % clear() + call active_surface_tallies % clear() call active_tallies % clear() ! Reset timers diff --git a/src/relaxng/tallies.rnc b/src/relaxng/tallies.rnc index 5ab8971e6c..204284c480 100644 --- a/src/relaxng/tallies.rnc +++ b/src/relaxng/tallies.rnc @@ -35,14 +35,14 @@ element tallies { element filter { (element id { xsd:int } | attribute id { xsd:int }) & ( - ( (element type { ( "cell" | "cellfrom" | "cellborn" | "material" | - "universe" | "surface" | "distribcell" | "mesh" | "energy" | - "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | - "energyfunction") } | - attribute type { ( "cell" | "cellfrom" | "cellborn" | "material" | - "universe" | "surface" | "distribcell" | "mesh" | "energy" | - "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | - "energyfunction") }) & + ( (element type { ( "cell" | "cellfrom" | "cellborn" | "material" | + "universe" | "surface" | "distribcell" | "mesh" | "energy" | + "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | + "energyfunction" | "meshsurface") } | + attribute type { ( "cell" | "cellfrom" | "cellborn" | "material" | + "universe" | "surface" | "distribcell" | "mesh" | "energy" | + "energyout" | "mu" | "polar" | "azimuthal" | "delayedgroup" | + "energyfunction" | "meshsurface") }) & (element bins { list { xsd:double+ } } | attribute bins { list { xsd:double+ } }) ) | diff --git a/src/relaxng/tallies.rng b/src/relaxng/tallies.rng index bad2fdce91..15b6f5b249 100644 --- a/src/relaxng/tallies.rng +++ b/src/relaxng/tallies.rng @@ -182,6 +182,7 @@ azimuthal delayedgroup energyfunction + meshsurface @@ -201,6 +202,7 @@ azimuthal delayedgroup energyfunction + meshsurface diff --git a/src/tallies/tally.F90 b/src/tallies/tally.F90 index 058c414f22..f4d12be7e1 100644 --- a/src/tallies/tally.F90 +++ b/src/tallies/tally.F90 @@ -3064,9 +3064,9 @@ contains ! tally total or partial currents between two cells !=============================================================================== - subroutine score_surface_tally(p) - - type(Particle), intent(in) :: p + subroutine score_surface_tally(p, tally_vec) + type(Particle), intent(in) :: p + type(VectorInt), intent(in) :: tally_vec integer :: i integer :: i_tally @@ -3086,9 +3086,9 @@ contains ! No collision, so no weight change when survival biasing flux = p % wgt - TALLY_LOOP: do i = 1, active_surface_tallies % size() + TALLY_LOOP: do i = 1, tally_vec % size() ! Get index of tally and pointer to tally - i_tally = active_surface_tallies % data(i) + i_tally = tally_vec % data(i) associate (t => tallies(i_tally) % obj) ! Find all valid bins in each filter if they have not already been found @@ -3188,134 +3188,6 @@ contains end subroutine score_surface_tally -!=============================================================================== -! SCORE_SURFACE_CURRENT tallies surface crossings in a mesh tally by manually -! determining which mesh surfaces were crossed -!=============================================================================== - - subroutine score_surface_current(p) - - type(Particle), intent(in) :: p - - integer :: i - integer :: i_tally - integer :: i_filt - integer :: i_bin - integer :: q ! loop index for scoring bins - integer :: k ! working index for expand and score - integer :: score_bin ! scoring bin, e.g. SCORE_FLUX - integer :: score_index ! scoring bin index - integer :: j ! loop index for scoring bins - integer :: filter_index ! single index for single bin - real(8) :: flux ! collision estimate of flux - real(8) :: filter_weight ! combined weight of all filters - real(8) :: score ! analog tally score - logical :: finished ! found all valid bin combinations - - ! No collision, so no weight change when survival biasing - flux = p % wgt - - TALLY_LOOP: do i = 1, active_current_tallies % size() - ! Get index of tally and pointer to tally - i_tally = active_current_tallies % data(i) - associate (t => tallies(i_tally) % obj) - - ! Find all valid bins in each filter if they have not already been found - ! for a previous tally. - do j = 1, size(t % filter) - i_filt = t % filter(j) - if (.not. filter_matches(i_filt) % bins_present) then - call filter_matches(i_filt) % bins % clear() - call filter_matches(i_filt) % weights % clear() - call filters(i_filt) % obj % get_all_bins(p, t % estimator, & - filter_matches(i_filt)) - filter_matches(i_filt) % bins_present = .true. - end if - ! If there are no valid bins for this filter, then there is nothing to - ! score and we can move on to the next tally. - if (filter_matches(i_filt) % bins % size() == 0) cycle TALLY_LOOP - - ! Set the index of the bin used in the first filter combination - filter_matches(i_filt) % i_bin = 1 - end do - - ! ======================================================================== - ! Loop until we've covered all valid bins on each of the filters. - - FILTER_LOOP: do - - ! Reset scoring index and weight - filter_index = 1 - filter_weight = ONE - - ! Determine scoring index and weight for this filter combination - do j = 1, size(t % filter) - i_filt = t % filter(j) - i_bin = filter_matches(i_filt) % i_bin - filter_index = filter_index + (filter_matches(i_filt) % bins % & - data(i_bin) - 1) * t % stride(j) - filter_weight = filter_weight * filter_matches(i_filt) % weights % & - data(i_bin) - end do - - ! Determine score - score = flux * filter_weight - - ! Currently only one score type - k = 0 - SCORE_LOOP: do q = 1, t % n_user_score_bins - k = k + 1 - - ! determine what type of score bin - score_bin = t % score_bins(q) - - ! determine scoring bin index, no offset from nuclide bins - score_index = q - - call expand_and_score(p, t, score_index, filter_index, score_bin, & - score, k) - end do SCORE_LOOP - - ! ====================================================================== - ! Filter logic - - ! Increment the filter bins, starting with the last filter to find the - ! next valid bin combination - finished = .true. - do j = size(t % filter), 1, -1 - i_filt = t % filter(j) - if (filter_matches(i_filt) % i_bin < filter_matches(i_filt) % & - bins % size()) then - filter_matches(i_filt) % i_bin = filter_matches(i_filt) % i_bin + 1 - finished = .false. - exit - else - filter_matches(i_filt) % i_bin = 1 - end if - end do - - ! Once we have finished all valid bins for each of the filters, exit - ! the loop. - if (finished) exit FILTER_LOOP - - end do FILTER_LOOP - - end associate - - ! If the user has specified that we can assume all tallies are spatially - ! separate, this implies that once a tally has been scored to, we needn't - ! check the others. This cuts down on overhead when there are many - ! tallies specified - - if (assume_separate) exit TALLY_LOOP - - end do TALLY_LOOP - - ! Reset filter matches flag - filter_matches(:) % bins_present = .false. - - end subroutine score_surface_current - !=============================================================================== ! APPLY_DERIVATIVE_TO_SCORE multiply the given score by its relative derivative !=============================================================================== @@ -4219,7 +4091,7 @@ contains call active_collision_tallies % clear() call active_tracklength_tallies % clear() call active_surface_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() do i = 1, n_tallies associate (t => tallies(i) % obj) @@ -4237,7 +4109,7 @@ contains call active_collision_tallies % push_back(i) end if elseif (t % type == TALLY_MESH_SURFACE) then - call active_current_tallies % push_back(i) + call active_meshsurf_tallies % push_back(i) elseif (t % type == TALLY_SURFACE) then call active_surface_tallies % push_back(i) end if diff --git a/src/tallies/tally_header.F90 b/src/tallies/tally_header.F90 index 6266005c2c..0495ce14dc 100644 --- a/src/tallies/tally_header.F90 +++ b/src/tallies/tally_header.F90 @@ -144,7 +144,7 @@ module tally_header ! Active tally lists type(VectorInt), public :: active_analog_tallies type(VectorInt), public :: active_tracklength_tallies - type(VectorInt), public :: active_current_tallies + type(VectorInt), public :: active_meshsurf_tallies type(VectorInt), public :: active_collision_tallies type(VectorInt), public :: active_tallies type(VectorInt), public :: active_surface_tallies @@ -418,7 +418,7 @@ contains ! Deallocate tally node lists call active_analog_tallies % clear() call active_tracklength_tallies % clear() - call active_current_tallies % clear() + call active_meshsurf_tallies % clear() call active_collision_tallies % clear() call active_surface_tallies % clear() call active_tallies % clear() diff --git a/src/tracking.F90 b/src/tracking.F90 index f5839eb8e9..3fe6a065b7 100644 --- a/src/tracking.F90 +++ b/src/tracking.F90 @@ -19,9 +19,9 @@ module tracking use surface_header use tally_header use tally, only: score_analog_tally, score_tracklength_tally, & - score_collision_tally, score_surface_current, & - score_track_derivative, score_surface_tally, & - score_collision_derivative, zero_flux_derivs + score_collision_tally, score_surface_tally, & + score_track_derivative, zero_flux_derivs, & + score_collision_derivative use track_output, only: initialize_particle_track, write_particle_track, & add_particle_track, finalize_particle_track @@ -185,7 +185,8 @@ contains p % event = EVENT_SURFACE end if ! Score cell to cell partial currents - if(active_surface_tallies % size() > 0) call score_surface_tally(p) + if(active_surface_tallies % size() > 0) & + call score_surface_tally(p, active_surface_tallies) else ! ==================================================================== ! PARTICLE HAS COLLISION @@ -200,7 +201,8 @@ contains ! since the direction of the particle will change and we need to use the ! pre-collision direction to figure out what mesh surfaces were crossed - if (active_current_tallies % size() > 0) call score_surface_current(p) + if (active_meshsurf_tallies % size() > 0) & + call score_surface_tally(p, active_meshsurf_tallies) ! Clear surface component p % surface = NONE @@ -317,12 +319,12 @@ contains ! forward slightly so that if the mesh boundary is on the surface, it is ! still processed - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then ! TODO: Find a better solution to score surface currents than ! physically moving the particle forward slightly p % coord(1) % xyz = p % coord(1) % xyz + TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) end if ! Score to global leakage tally @@ -350,10 +352,10 @@ contains ! particle to change -- artificially move the particle slightly back in ! case the surface crossing is coincident with a mesh boundary - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then xyz = p % coord(1) % xyz p % coord(1) % xyz = p % coord(1) % xyz - TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) p % coord(1) % xyz = xyz end if @@ -407,10 +409,10 @@ contains ! Score surface currents since reflection causes the direction of the ! particle to change -- artificially move the particle slightly back in ! case the surface crossing is coincident with a mesh boundary - if (active_current_tallies % size() > 0) then + if (active_meshsurf_tallies % size() > 0) then xyz = p % coord(1) % xyz p % coord(1) % xyz = p % coord(1) % xyz - TINY_BIT * p % coord(1) % uvw - call score_surface_current(p) + call score_surface_tally(p, active_meshsurf_tallies) p % coord(1) % xyz = xyz end if diff --git a/tests/regression_tests/filter_mesh/inputs_true.dat b/tests/regression_tests/filter_mesh/inputs_true.dat index ca063b7ce9..511b298482 100644 --- a/tests/regression_tests/filter_mesh/inputs_true.dat +++ b/tests/regression_tests/filter_mesh/inputs_true.dat @@ -327,18 +327,27 @@ 1 + + 1 + 2 + + 2 + 3 + + 3 + 1 total - 1 + 4 current @@ -346,7 +355,7 @@ total - 2 + 5 current @@ -354,7 +363,7 @@ total - 3 + 6 current diff --git a/tests/regression_tests/filter_mesh/results_true.dat b/tests/regression_tests/filter_mesh/results_true.dat index ac3439da50..f331238b70 100644 --- a/tests/regression_tests/filter_mesh/results_true.dat +++ b/tests/regression_tests/filter_mesh/results_true.dat @@ -1 +1 @@ -804d161cb8eae506d3247a533d122f44a01d3cedd566b3c65c71a0b51326dd9b97f8bbf45af7304b500476f3f854d91b10ccad94122d15f23641b05b835fada6 \ No newline at end of file +46950c046648faaa5ff3cb7b4fdd03667ae3c6da96a7ed8121761291de452cf88481f53e967ed52407d77d90109ae24839967a22ae216531a0e1491f5051ea72 \ No newline at end of file diff --git a/tests/regression_tests/filter_mesh/test.py b/tests/regression_tests/filter_mesh/test.py index e0c6dd0f2f..8a7f7a6fca 100644 --- a/tests/regression_tests/filter_mesh/test.py +++ b/tests/regression_tests/filter_mesh/test.py @@ -30,6 +30,9 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): mesh_1d_filter = openmc.MeshFilter(mesh_1d) mesh_2d_filter = openmc.MeshFilter(mesh_2d) mesh_3d_filter = openmc.MeshFilter(mesh_3d) + meshsurf_1d_filter = openmc.MeshSurfaceFilter(mesh_1d) + meshsurf_2d_filter = openmc.MeshSurfaceFilter(mesh_2d) + meshsurf_3d_filter = openmc.MeshSurfaceFilter(mesh_3d) # Initialized the tallies tally = openmc.Tally(name='tally 1') @@ -38,7 +41,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 2') - tally.filters = [mesh_1d_filter] + tally.filters = [meshsurf_1d_filter] tally.scores = ['current'] self._model.tallies.append(tally) @@ -48,7 +51,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 4') - tally.filters = [mesh_2d_filter] + tally.filters = [meshsurf_2d_filter] tally.scores = ['current'] self._model.tallies.append(tally) @@ -58,7 +61,7 @@ class FilterMeshTestHarness(HashedPyAPITestHarness): self._model.tallies.append(tally) tally = openmc.Tally(name='tally 6') - tally.filters = [mesh_3d_filter] + tally.filters = [meshsurf_3d_filter] tally.scores = ['current'] self._model.tallies.append(tally) diff --git a/tests/regression_tests/score_current/results_true.dat b/tests/regression_tests/score_current/results_true.dat index 75d61b7188..dedc473de9 100644 --- a/tests/regression_tests/score_current/results_true.dat +++ b/tests/regression_tests/score_current/results_true.dat @@ -1 +1 @@ -4675d5101f4f829369c39cb33d654430836b934ab07c165777ba6e214bdf3a698b8082f4f9bb9e78f1f0e495b30ea02cf9b3d14622c59915d818d678a1e5b7b1 \ No newline at end of file +138b312cdaa822c9b62f757b3259522004b679c4ed289a92798b29a6442c26d12c53256635be273f13e3703816ff50a1b9f52d79770eade01e482384ac0d389f \ No newline at end of file diff --git a/tests/regression_tests/score_current/tallies.xml b/tests/regression_tests/score_current/tallies.xml index 3b8f60adba..a381e4c2e2 100644 --- a/tests/regression_tests/score_current/tallies.xml +++ b/tests/regression_tests/score_current/tallies.xml @@ -9,7 +9,7 @@ - mesh + meshsurface 1 From 22429dd389b5e6a297473ebcbc0fa1114dff7ad1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 16 Mar 2018 09:34:16 -0500 Subject: [PATCH 209/212] Implement MeshSurfaceFilter.get_pandas_dataframe. Fix surface/mesh filters --- openmc/filter.py | 164 ++++++++++++++++++++++++++++++++++++++-------- openmc/tallies.py | 2 +- 2 files changed, 136 insertions(+), 30 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index d7b8267e96..7fa47cb4df 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -22,12 +22,14 @@ _FILTER_TYPES = ['universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy', 'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup', 'energyfunction', 'cellfrom'] -_CURRENT_NAMES = {1: 'x-min out', 2: 'x-min in', - 3: 'x-max out', 4: 'x-max in', - 5: 'y-min out', 6: 'y-min in', - 7: 'y-max out', 8: 'y-max in', - 9: 'z-min out', 10: 'z-min in', - 11: 'z-max out', 12: 'z-max in'} +_CURRENT_NAMES = OrderedDict([ + (1, 'x-min out'), (2, 'x-min in'), + (3, 'x-max out'), (4, 'x-max in'), + (5, 'y-min out'), (6, 'y-min in'), + (7, 'y-max out'), (8, 'y-max in'), + (9, 'z-min out'), (10, 'z-min in'), + (11, 'z-max out'), (12, 'z-max in') +]) class FilterMeta(ABCMeta): @@ -497,9 +499,9 @@ class CellFilter(WithIDFilter): Parameters ---------- - bins : openmc.Cell, Integral, or iterable thereof - The Cells to tally. Either openmc.Cell objects or their - Integral ID numbers can be used. + bins : openmc.Cell, int, or iterable thereof + The cells to tally. Either openmc.Cell objects or their ID numbers can + be used. filter_id : int Unique identifier for the filter @@ -565,21 +567,21 @@ class CellbornFilter(WithIDFilter): class SurfaceFilter(Filter): - """Bins particle currents on Mesh surfaces. + """Filters particles by surface crossing Parameters ---------- - bins : Iterable of Integral - Indices corresponding to which face of a mesh cell the current is - crossing. + bins : openmc.Surface, int, or iterable of Integral + The surfaces to tally over. Either openmc.Surface objects of their ID + numbers can be used. filter_id : int Unique identifier for the filter Attributes ---------- bins : Iterable of Integral - Indices corresponding to which face of a mesh cell the current is - crossing. + The surfaces to tally over. Either openmc.Surface objects of their ID + numbers can be used. id : int Unique identifier for the filter num_bins : Integral @@ -598,13 +600,6 @@ class SurfaceFilter(Filter): self._bins = bins - @property - def num_bins(self): - # Need to handle number of bins carefully -- for surface current - # tallies, the number of bins depends on the mesh, which we don't have a - # reference to in this filter - return self._num_bins - def get_pandas_dataframe(self, data_size, stride, **kwargs): """Builds a Pandas DataFrame for the Filter's bins. @@ -689,7 +684,6 @@ class MeshFilter(Filter): filter_id = int(group.name.split('/')[-1].lstrip('filter ')) out = cls(mesh_obj, filter_id=filter_id) - out._num_bins = group['n_bins'].value return out @@ -705,10 +699,7 @@ class MeshFilter(Filter): @property def num_bins(self): - try: - return self._num_bins - except AttributeError: - return reduce(operator.mul, self.mesh.dimension) + return reduce(operator.mul, self.mesh.dimension) def check_bins(self, bins): if not len(bins) == 1: @@ -802,7 +793,7 @@ class MeshFilter(Filter): filter_dict = {} # Append Mesh ID as outermost index of multi-index - mesh_key = 'mesh {0}'.format(self.mesh.id) + mesh_key = 'mesh {}'.format(self.mesh.id) # Find mesh dimensions - use 3D indices for simplicity n_dim = len(self.mesh.dimension) @@ -846,7 +837,122 @@ class MeshFilter(Filter): class MeshSurfaceFilter(MeshFilter): - pass + """Filter events by surface crossings on a regular, rectangular mesh. + + Parameters + ---------- + mesh : openmc.Mesh + The Mesh object that events will be tallied onto + filter_id : int + Unique identifier for the filter + + Attributes + ---------- + bins : Integral + The Mesh ID + mesh : openmc.Mesh + The Mesh object that events will be tallied onto + id : int + Unique identifier for the filter + num_bins : Integral + The number of filter bins + + """ + + @property + def num_bins(self): + n_dim = len(self.mesh.dimension) + return 4*n_dim*reduce(operator.mul, self.mesh.dimension) + + def get_bin_index(self, filter_bin): + raise NotImplementedError + + def get_bin(self, bin_index): + raise NotImplementedError + + def get_pandas_dataframe(self, data_size, stride, **kwargs): + """Builds a Pandas DataFrame for the Filter's bins. + + This method constructs a Pandas DataFrame object for the filter with + columns annotated by filter bin information. This is a helper method for + :meth:`Tally.get_pandas_dataframe`. + + Parameters + ---------- + data_size : int + The total number of bins in the tally corresponding to this filter + stride : int + Stride in memory for the filter + + Returns + ------- + pandas.DataFrame + A Pandas DataFrame with three columns describing the x,y,z mesh + cell indices corresponding to each filter bin. The number of rows + in the DataFrame is the same as the total number of bins in the + corresponding tally, with the filter bin appropriately tiled to map + to the corresponding tally bins. + + See also + -------- + Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() + + """ + # Initialize Pandas DataFrame + df = pd.DataFrame() + + # Initialize dictionary to build Pandas Multi-index column + filter_dict = {} + + # Append Mesh ID as outermost index of multi-index + mesh_key = 'mesh {}'.format(self.mesh.id) + + # Find mesh dimensions - use 3D indices for simplicity + if len(self.mesh.dimension) == 3: + nx, ny, nz = self.mesh.dimension + elif len(self.mesh.dimension) == 2: + nx, ny = self.mesh.dimension + nz = 1 + else: + nx = self.mesh.dimension + ny = nz = 1 + + # Generate multi-index sub-column for x-axis + filter_bins = np.arange(1, nx + 1) + repeat_factor = 12 * stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'x')] = filter_bins + + # Generate multi-index sub-column for y-axis + filter_bins = np.arange(1, ny + 1) + repeat_factor = 12 * nx * stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'y')] = filter_bins + + # Generate multi-index sub-column for z-axis + filter_bins = np.arange(1, nz + 1) + repeat_factor = 12 * nx * ny * stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'z')] = filter_bins + + # Generate multi-index sub-column for surface + filter_bins = list(_CURRENT_NAMES.values()) + repeat_factor = stride + filter_bins = np.repeat(filter_bins, repeat_factor) + tile_factor = data_size // len(filter_bins) + filter_bins = np.tile(filter_bins, tile_factor) + filter_dict[(mesh_key, 'surf')] = filter_bins + + # Initialize a Pandas DataFrame from the mesh dictionary + df = pd.concat([df, pd.DataFrame(filter_dict)]) + + return df class RealFilter(Filter): diff --git a/openmc/tallies.py b/openmc/tallies.py index d8bc2136a1..6c055d1913 100644 --- a/openmc/tallies.py +++ b/openmc/tallies.py @@ -2738,7 +2738,7 @@ class Tally(IDManagerMixin): new_filter = filter_type(bins) # Set number of bins manually for mesh/distribcell filters - if filter_type in (openmc.DistribcellFilter, openmc.MeshFilter): + if filter_type is openmc.DistribcellFilter: new_filter._num_bins = find_filter._num_bins # Replace existing filter with new one From d393a74906d811e81f1700b8286dbb2b62e16e97 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Fri, 16 Mar 2018 14:38:37 -0500 Subject: [PATCH 210/212] Implement get_bin and get_bin_index for MeshSurfaceFilter --- docs/source/pythonapi/base.rst | 1 + openmc/filter.py | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/source/pythonapi/base.rst b/docs/source/pythonapi/base.rst index f1633f3f9d..070b5bd201 100644 --- a/docs/source/pythonapi/base.rst +++ b/docs/source/pythonapi/base.rst @@ -109,6 +109,7 @@ Constructing Tallies openmc.CellbornFilter openmc.SurfaceFilter openmc.MeshFilter + openmc.MeshSurfaceFilter openmc.EnergyFilter openmc.EnergyoutFilter openmc.MuFilter diff --git a/openmc/filter.py b/openmc/filter.py index 7fa47cb4df..26d81112f1 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -865,10 +865,25 @@ class MeshSurfaceFilter(MeshFilter): return 4*n_dim*reduce(operator.mul, self.mesh.dimension) def get_bin_index(self, filter_bin): - raise NotImplementedError + # Split bin into mesh/surface parts + *mesh_tuple, surf = filter_bin + + # Get index for mesh alone + mesh_index = super().get_bin_index(mesh_tuple) + + # Combine surface and mesh index + n_dim = len(self.mesh.dimension) + for surf_index, name in _CURRENT_NAMES.items(): + if surf == name: + return 4*n_dim*mesh_index + surf_index - 1 + else: + raise ValueError("'{}' is not a valid mesh surface.".format(surf)) def get_bin(self, bin_index): - raise NotImplementedError + n_dim = len(self.mesh.dimension) + mesh_index, surf_index = divmod(bin_index, 4*n_dim) + mesh_bin = super().get_bin(mesh_index) + return mesh_bin + (_CURRENT_NAMES[surf_index + 1],) def get_pandas_dataframe(self, data_size, stride, **kwargs): """Builds a Pandas DataFrame for the Filter's bins. From 0da649fd903f2902fe44de471ae2906dacfbf462 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Mon, 19 Mar 2018 18:12:59 -0500 Subject: [PATCH 211/212] Simplify use of _CURRENT_NAMES in filter.py --- examples/xml/pincell/tallies.xml | 2 +- openmc/filter.py | 81 +++++--------------------------- 2 files changed, 14 insertions(+), 69 deletions(-) diff --git a/examples/xml/pincell/tallies.xml b/examples/xml/pincell/tallies.xml index 0ae36eceda..7e1e0dafe4 100644 --- a/examples/xml/pincell/tallies.xml +++ b/examples/xml/pincell/tallies.xml @@ -8,7 +8,7 @@ - 1 + 2 diff --git a/openmc/filter.py b/openmc/filter.py index 26d81112f1..2a36a66e05 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -15,6 +15,7 @@ import openmc.checkvalue as cv from .cell import Cell from .material import Material from .mixin import IDManagerMixin +from .surface import Surface from .universe import Universe @@ -22,14 +23,11 @@ _FILTER_TYPES = ['universe', 'material', 'cell', 'cellborn', 'surface', 'mesh', 'energy', 'energyout', 'mu', 'polar', 'azimuthal', 'distribcell', 'delayedgroup', 'energyfunction', 'cellfrom'] -_CURRENT_NAMES = OrderedDict([ - (1, 'x-min out'), (2, 'x-min in'), - (3, 'x-max out'), (4, 'x-max in'), - (5, 'y-min out'), (6, 'y-min in'), - (7, 'y-max out'), (8, 'y-max in'), - (9, 'z-min out'), (10, 'z-min in'), - (11, 'z-max out'), (12, 'z-max in') -]) +_CURRENT_NAMES = ( + 'x-min out', 'x-min in', 'x-max out', 'x-max in', + 'y-min out', 'y-min in', 'y-max out', 'y-max in', + 'z-min out', 'z-min in', 'z-max out', 'z-max in' +) class FilterMeta(ABCMeta): @@ -566,7 +564,7 @@ class CellbornFilter(WithIDFilter): expected_type = Cell -class SurfaceFilter(Filter): +class SurfaceFilter(WithIDFilter): """Filters particles by surface crossing Parameters @@ -588,57 +586,7 @@ class SurfaceFilter(Filter): The number of filter bins """ - @Filter.bins.setter - def bins(self, bins): - # Format the bins as a 1D numpy array. - bins = np.atleast_1d(bins) - - # Check the bin values. - cv.check_iterable_type('filter bins', bins, Integral) - for edge in bins: - cv.check_greater_than('filter bin', edge, 0, equality=True) - - self._bins = bins - - def get_pandas_dataframe(self, data_size, stride, **kwargs): - """Builds a Pandas DataFrame for the Filter's bins. - - This method constructs a Pandas DataFrame object for the filter with - columns annotated by filter bin information. This is a helper method for - :meth:`Tally.get_pandas_dataframe`. - - Parameters - ---------- - data_size : int - The total number of bins in the tally corresponding to this filter - stride : int - Stride in memory for the filter - - Returns - ------- - pandas.DataFrame - A Pandas DataFrame with a column of strings describing which surface - the current is crossing and which direction it points. The number - of rows in the DataFrame is the same as the total number of bins in - the corresponding tally, with the filter bin appropriately tiled to - map to the corresponding tally bins. - - See also - -------- - Tally.get_pandas_dataframe(), CrossFilter.get_pandas_dataframe() - - """ - # Initialize Pandas DataFrame - df = pd.DataFrame() - - filter_bins = np.repeat(self.bins, stride) - tile_factor = data_size // len(filter_bins) - filter_bins = np.tile(filter_bins, tile_factor) - filter_bins = [_CURRENT_NAMES[x] for x in filter_bins] - df = pd.concat([df, pd.DataFrame( - {self.short_name.lower(): filter_bins})]) - - return df + expected_type = Surface class MeshFilter(Filter): @@ -873,9 +821,9 @@ class MeshSurfaceFilter(MeshFilter): # Combine surface and mesh index n_dim = len(self.mesh.dimension) - for surf_index, name in _CURRENT_NAMES.items(): + for surf_index, name in enumerate(_CURRENT_NAMES): if surf == name: - return 4*n_dim*mesh_index + surf_index - 1 + return 4*n_dim*mesh_index + surf_index else: raise ValueError("'{}' is not a valid mesh surface.".format(surf)) @@ -883,7 +831,7 @@ class MeshSurfaceFilter(MeshFilter): n_dim = len(self.mesh.dimension) mesh_index, surf_index = divmod(bin_index, 4*n_dim) mesh_bin = super().get_bin(mesh_index) - return mesh_bin + (_CURRENT_NAMES[surf_index + 1],) + return mesh_bin + (_CURRENT_NAMES[surf_index],) def get_pandas_dataframe(self, data_size, stride, **kwargs): """Builds a Pandas DataFrame for the Filter's bins. @@ -957,17 +905,14 @@ class MeshSurfaceFilter(MeshFilter): filter_dict[(mesh_key, 'z')] = filter_bins # Generate multi-index sub-column for surface - filter_bins = list(_CURRENT_NAMES.values()) repeat_factor = stride - filter_bins = np.repeat(filter_bins, repeat_factor) + filter_bins = np.repeat(_CURRENT_NAMES, repeat_factor) tile_factor = data_size // len(filter_bins) filter_bins = np.tile(filter_bins, tile_factor) filter_dict[(mesh_key, 'surf')] = filter_bins # Initialize a Pandas DataFrame from the mesh dictionary - df = pd.concat([df, pd.DataFrame(filter_dict)]) - - return df + return pd.concat([df, pd.DataFrame(filter_dict)]) class RealFilter(Filter): From e1da965f707cbb66c1b099ce68d3a18c206ee0d1 Mon Sep 17 00:00:00 2001 From: Paul Romano Date: Tue, 20 Mar 2018 14:15:56 -0500 Subject: [PATCH 212/212] Fix typos (thanks @smharper) --- openmc/filter.py | 4 ++-- src/input_xml.F90 | 4 +--- src/tallies/tally_filter_meshsurface.F90 | 4 ++-- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/openmc/filter.py b/openmc/filter.py index 2a36a66e05..c1b9f8dc92 100644 --- a/openmc/filter.py +++ b/openmc/filter.py @@ -570,7 +570,7 @@ class SurfaceFilter(WithIDFilter): Parameters ---------- bins : openmc.Surface, int, or iterable of Integral - The surfaces to tally over. Either openmc.Surface objects of their ID + The surfaces to tally over. Either openmc.Surface objects or their ID numbers can be used. filter_id : int Unique identifier for the filter @@ -578,7 +578,7 @@ class SurfaceFilter(WithIDFilter): Attributes ---------- bins : Iterable of Integral - The surfaces to tally over. Either openmc.Surface objects of their ID + The surfaces to tally over. Either openmc.Surface objects or their ID numbers can be used. id : int Unique identifier for the filter diff --git a/src/input_xml.F90 b/src/input_xml.F90 index a0b077a940..a29bb08e83 100644 --- a/src/input_xml.F90 +++ b/src/input_xml.F90 @@ -2371,9 +2371,7 @@ contains ! Allocate according to the filter type err = openmc_filter_set_type(i_start + i - 1, to_c_string(temp_str)) - if (err /= 0) then - call fatal_error(to_f_string(openmc_err_msg)) - end if + if (err /= 0) call fatal_error(to_f_string(openmc_err_msg)) ! Read filter data from XML call f % obj % from_xml(node_filt) diff --git a/src/tallies/tally_filter_meshsurface.F90 b/src/tallies/tally_filter_meshsurface.F90 index 1913c8b0de..e1e8c48033 100644 --- a/src/tallies/tally_filter_meshsurface.F90 +++ b/src/tallies/tally_filter_meshsurface.F90 @@ -48,7 +48,7 @@ contains n = node_word_count(node, "bins") if (n /= 1) call fatal_error("Only one mesh can be & - &specified per mesh filter.") + &specified per meshsurface filter.") ! Determine id of mesh call get_node_value(node, "bins", id) @@ -297,7 +297,7 @@ contains !=============================================================================== function openmc_meshsurface_filter_set_mesh(index, index_mesh) result(err) bind(C) - ! Set the mesh for a mesh filter + ! Set the mesh for a mesh surface filter integer(C_INT32_T), value, intent(in) :: index integer(C_INT32_T), value, intent(in) :: index_mesh integer(C_INT) :: err