Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 13 additions & 14 deletions openmc/stats/univariate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1627,21 +1627,20 @@ def _sample_unbiased(self, n_samples: int = 1, seed: int | None = None):
samples_out = p_i

elif self.interpolation == 'linear-linear':
# get variable and probability values for the
# next entry
x_i1 = self.x[cdf_idx + 1]
p_i1 = p[cdf_idx + 1]
# compute slope between entries
m = (p_i1 - p_i) / (x_i1 - x_i)
# set values for zero slope
zero = m == 0.0
m[zero] = x_i[zero] + (xi[zero] - c_i[zero]) / p_i[zero]
# set values for non-zero slope
non_zero = ~zero
quad = np.power(p_i[non_zero], 2) + 2.0 * m[non_zero] * (xi[non_zero] - c_i[non_zero])
quad[quad < 0.0] = 0.0
m[non_zero] = x_i[non_zero] + (np.sqrt(quad) - p_i[non_zero]) / m[non_zero]
samples_out = m
# At fraction u of the bin mass, the squared density interpolates
# linearly between the two squared endpoint densities.
area = xi - c_i
mass = cdf[cdf_idx + 1] - c_i
u = np.divide(area, mass, out=np.zeros_like(area), where=mass > 0)
density = np.hypot(np.sqrt(1 - u)*p_i, np.sqrt(u)*p_i1)

# Area equals the offset times the mean density on that interval.
# This also holds for a flat PDF and avoids subtracting close roots.
avg_density = 0.5*p_i + 0.5*density
offset = np.divide(area, avg_density, out=np.zeros_like(area),
where=avg_density > 0)
samples_out = x_i + offset
elif self.interpolation == "linear-log":
# get variable and probability values for the
# next entry
Expand Down
16 changes: 16 additions & 0 deletions tests/unit_tests/test_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,22 @@ def test_tabular():
assert np.all(weights != 1.0)


@pytest.mark.parametrize('heights', [
(1.0, 1.0 + 2.0**-50), (1.0, 1.0 - 2.0**-50),
(1.0, 1.0), (0.0, 2.0), (2.0, 0.0),
])
def test_tabular_linear_linear_quantiles(heights):
d = openmc.stats.Tabular([0.0, 1.0], heights, 'linear-linear')
x, weights = d.sample(32, seed=17)

# Integrating the linear PDF up to each sample recovers the uniform draw.
left, right = heights
cdf = (2.0*left*x + (right - left)*x**2) / (left + right)
uniform = np.random.RandomState(17).random_sample(x.size)
np.testing.assert_allclose(cdf, uniform, rtol=0.0, atol=2e-14)
np.testing.assert_array_equal(weights, np.ones_like(x))


def test_tabular_from_xml():
x = np.array([0.0, 5.0, 7.0, 10.0])
p = np.array([10.0, 20.0, 5.0, 6.0])
Expand Down
Loading