Prepare for NumPy 2.0 (#2845)

This commit is contained in:
Paul Romano 2024-03-26 11:00:06 -05:00 committed by GitHub
parent ce7efa415e
commit 9fee6534b6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 74 additions and 72 deletions

View file

@ -113,7 +113,7 @@ class CorrelatedAngleEnergy(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_(self._name)
group.attrs['type'] = np.bytes_(self._name)
dset = group.create_dataset('energy', data=self.energy)
dset.attrs['interpolation'] = np.vstack((self.breakpoints,

View file

@ -277,7 +277,7 @@ class MaxwellEnergy(EnergyDistribution):
"""
group.attrs['type'] = np.string_('maxwell')
group.attrs['type'] = np.bytes_('maxwell')
group.attrs['u'] = self.u
self.theta.to_hdf5(group, 'theta')
@ -410,7 +410,7 @@ class Evaporation(EnergyDistribution):
"""
group.attrs['type'] = np.string_('evaporation')
group.attrs['type'] = np.bytes_('evaporation')
group.attrs['u'] = self.u
self.theta.to_hdf5(group, 'theta')
@ -556,7 +556,7 @@ class WattEnergy(EnergyDistribution):
"""
group.attrs['type'] = np.string_('watt')
group.attrs['type'] = np.bytes_('watt')
group.attrs['u'] = self.u
self.a.to_hdf5(group, 'a')
self.b.to_hdf5(group, 'b')
@ -728,7 +728,7 @@ class MadlandNix(EnergyDistribution):
"""
group.attrs['type'] = np.string_('madland-nix')
group.attrs['type'] = np.bytes_('madland-nix')
group.attrs['efl'] = self.efl
group.attrs['efh'] = self.efh
self.tm.to_hdf5(group)
@ -846,7 +846,7 @@ class DiscretePhoton(EnergyDistribution):
"""
group.attrs['type'] = np.string_('discrete_photon')
group.attrs['type'] = np.bytes_('discrete_photon')
group.attrs['primary_flag'] = self.primary_flag
group.attrs['energy'] = self.energy
group.attrs['atomic_weight_ratio'] = self.atomic_weight_ratio
@ -945,7 +945,7 @@ class LevelInelastic(EnergyDistribution):
"""
group.attrs['type'] = np.string_('level')
group.attrs['type'] = np.bytes_('level')
group.attrs['threshold'] = self.threshold
group.attrs['mass_ratio'] = self.mass_ratio
@ -1074,7 +1074,7 @@ class ContinuousTabular(EnergyDistribution):
"""
group.attrs['type'] = np.string_('continuous')
group.attrs['type'] = np.bytes_('continuous')
dset = group.create_dataset('energy', data=self.energy)
dset.attrs['interpolation'] = np.vstack((self.breakpoints,

View file

@ -364,7 +364,7 @@ class Tabulated1D(Function1D):
"""
dataset = group.create_dataset(name, data=np.vstack(
[self.x, self.y]))
dataset.attrs['type'] = np.string_(type(self).__name__)
dataset.attrs['type'] = np.bytes_(type(self).__name__)
dataset.attrs['breakpoints'] = self.breakpoints
dataset.attrs['interpolation'] = self.interpolation
@ -460,7 +460,7 @@ class Polynomial(np.polynomial.Polynomial, Function1D):
"""
dataset = group.create_dataset(name, data=self.coef)
dataset.attrs['type'] = np.string_(type(self).__name__)
dataset.attrs['type'] = np.bytes_(type(self).__name__)
@classmethod
def from_hdf5(cls, dataset):
@ -592,7 +592,7 @@ class Sum(Function1D):
"""
sum_group = group.create_group(name)
sum_group.attrs['type'] = np.string_(type(self).__name__)
sum_group.attrs['type'] = np.bytes_(type(self).__name__)
sum_group.attrs['n'] = len(self.functions)
for i, f in enumerate(self.functions):
f.to_hdf5(sum_group, f'func_{i+1}')

View file

@ -366,7 +366,7 @@ class KalbachMann(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('kalbach-mann')
group.attrs['type'] = np.bytes_('kalbach-mann')
dset = group.create_dataset('energy', data=self.energy)
dset.attrs['interpolation'] = np.vstack((self.breakpoints,

View file

@ -1273,7 +1273,7 @@ class WindowedMultipole(EqualityMixin):
# Open file and write version.
with h5py.File(str(path), mode, libver=libver) as f:
f.attrs['filetype'] = np.string_('data_wmp')
f.attrs['filetype'] = np.bytes_('data_wmp')
f.attrs['version'] = np.array(WMP_VERSION)
g = f.create_group(self.name)

View file

@ -91,7 +91,7 @@ class NBodyPhaseSpace(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('nbody')
group.attrs['type'] = np.bytes_('nbody')
group.attrs['total_mass'] = self.total_mass
group.attrs['n_particles'] = self.n_particles
group.attrs['atomic_weight_ratio'] = self.atomic_weight_ratio

View file

@ -425,7 +425,7 @@ class IncidentNeutron(EqualityMixin):
# Open file and write version
with h5py.File(str(path), mode, libver=libver) as f:
f.attrs['filetype'] = np.string_('data_neutron')
f.attrs['filetype'] = np.bytes_('data_neutron')
f.attrs['version'] = np.array(HDF5_VERSION)
# Write basic data

View file

@ -764,7 +764,7 @@ class IncidentPhoton(EqualityMixin):
"""
with h5py.File(str(path), mode, libver=libver) as f:
# Write filetype and version
f.attrs['filetype'] = np.string_('data_photon')
f.attrs['filetype'] = np.bytes_('data_photon')
if 'version' not in f.attrs:
f.attrs['version'] = np.array(HDF5_VERSION)

View file

@ -124,8 +124,8 @@ class Product(EqualityMixin):
HDF5 group to write to
"""
group.attrs['particle'] = np.string_(self.particle)
group.attrs['emission_mode'] = np.string_(self.emission_mode)
group.attrs['particle'] = np.bytes_(self.particle)
group.attrs['emission_mode'] = np.bytes_(self.emission_mode)
if self.decay_rate > 0.0:
group.attrs['decay_rate'] = self.decay_rate

View file

@ -920,9 +920,9 @@ class Reaction(EqualityMixin):
group.attrs['mt'] = self.mt
if self.mt in REACTION_NAME:
group.attrs['label'] = np.string_(REACTION_NAME[self.mt])
group.attrs['label'] = np.bytes_(REACTION_NAME[self.mt])
else:
group.attrs['label'] = np.string_(self.mt)
group.attrs['label'] = np.bytes_(self.mt)
group.attrs['Q_value'] = self.q_value
group.attrs['center_of_mass'] = 1 if self.center_of_mass else 0
group.attrs['redundant'] = 1 if self.redundant else 0

View file

@ -239,14 +239,14 @@ class ResonanceCovarianceRange:
samples = []
# Handling MLBW/SLBW sampling
rng = np.random.default_rng()
if formalism == 'mlbw' or formalism == 'slbw':
params = ['energy', 'neutronWidth', 'captureWidth', 'fissionWidth',
'competitiveWidth']
param_list = params[:mpar]
mean_array = parameters[param_list].values
mean = mean_array.flatten()
par_samples = np.random.multivariate_normal(mean, cov,
size=n_samples)
par_samples = rng.multivariate_normal(mean, cov, size=n_samples)
spin = parameters['J'].values
l_value = parameters['L'].values
for sample in par_samples:
@ -277,8 +277,7 @@ class ResonanceCovarianceRange:
param_list = params[:mpar]
mean_array = parameters[param_list].values
mean = mean_array.flatten()
par_samples = np.random.multivariate_normal(mean, cov,
size=n_samples)
par_samples = rng.multivariate_normal(mean, cov, size=n_samples)
spin = parameters['J'].values
l_value = parameters['L'].values
for sample in par_samples:

View file

@ -221,7 +221,7 @@ class CoherentElastic(Function1D):
"""
dataset = group.create_dataset(name, data=np.vstack(
[self.bragg_edges, self.factors]))
dataset.attrs['type'] = np.string_(type(self).__name__)
dataset.attrs['type'] = np.bytes_(type(self).__name__)
@classmethod
def from_hdf5(cls, dataset):
@ -294,7 +294,7 @@ class IncoherentElastic(Function1D):
"""
data = np.array([self.bound_xs, self.debye_waller])
dataset = group.create_dataset(name, data=data)
dataset.attrs['type'] = np.string_(type(self).__name__)
dataset.attrs['type'] = np.bytes_(type(self).__name__)
@classmethod
def from_hdf5(cls, dataset):
@ -464,7 +464,7 @@ class ThermalScattering(EqualityMixin):
"""
# Open file and write version
with h5py.File(str(path), mode, libver=libver) as f:
f.attrs['filetype'] = np.string_('data_thermal')
f.attrs['filetype'] = np.bytes_('data_thermal')
f.attrs['version'] = np.array(HDF5_VERSION)
# Write basic data

View file

@ -43,7 +43,7 @@ class CoherentElasticAE(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('coherent_elastic')
group.attrs['type'] = np.bytes_('coherent_elastic')
self.coherent_xs.to_hdf5(group, 'coherent_xs')
@classmethod
@ -104,7 +104,7 @@ class IncoherentElasticAE(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('incoherent_elastic')
group.attrs['type'] = np.bytes_('incoherent_elastic')
group.create_dataset('debye_waller', data=self.debye_waller)
@classmethod
@ -146,7 +146,7 @@ class IncoherentElasticAEDiscrete(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('incoherent_elastic_discrete')
group.attrs['type'] = np.bytes_('incoherent_elastic_discrete')
group.create_dataset('mu_out', data=self.mu_out)
@classmethod
@ -203,7 +203,7 @@ class IncoherentInelasticAEDiscrete(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('incoherent_inelastic_discrete')
group.attrs['type'] = np.bytes_('incoherent_inelastic_discrete')
group.create_dataset('energy_out', data=self.energy_out)
group.create_dataset('mu_out', data=self.mu_out)
group.create_dataset('skewed', data=self.skewed)
@ -266,7 +266,7 @@ class MixedElasticAE(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('mixed_elastic')
group.attrs['type'] = np.bytes_('mixed_elastic')
coherent_group = group.create_group('coherent')
self.coherent.to_hdf5(coherent_group)
incoherent_group = group.create_group('incoherent')

View file

@ -63,7 +63,7 @@ class UncorrelatedAngleEnergy(AngleEnergy):
HDF5 group to write to
"""
group.attrs['type'] = np.string_('uncorrelated')
group.attrs['type'] = np.bytes_('uncorrelated')
if self.angle is not None:
angle_group = group.create_group('angle')
self.angle.to_hdf5(angle_group)

View file

@ -291,7 +291,7 @@ class StepResult:
# Store concentration mat and nuclide dictionaries (along with volumes)
handle.attrs['version'] = np.array(VERSION_RESULTS)
handle.attrs['filetype'] = np.string_('depletion results')
handle.attrs['filetype'] = np.bytes_('depletion results')
mat_list = sorted(self.mat_to_hdf5_ind, key=int)
nuc_list = sorted(self.index_nuc)

View file

@ -1964,7 +1964,7 @@ class XSdata:
grp.attrs['fissionable'] = self.fissionable
if self.representation is not None:
grp.attrs['representation'] = np.string_(self.representation)
grp.attrs['representation'] = np.bytes_(self.representation)
if self.representation == REPRESENTATION_ANGLE:
if self.num_azimuthal is not None:
grp.attrs['num_azimuthal'] = self.num_azimuthal
@ -1972,9 +1972,9 @@ class XSdata:
if self.num_polar is not None:
grp.attrs['num_polar'] = self.num_polar
grp.attrs['scatter_shape'] = np.string_("[G][G'][Order]")
grp.attrs['scatter_shape'] = np.bytes_("[G][G'][Order]")
if self.scatter_format is not None:
grp.attrs['scatter_format'] = np.string_(self.scatter_format)
grp.attrs['scatter_format'] = np.bytes_(self.scatter_format)
if self.order is not None:
grp.attrs['order'] = self.order
@ -2516,7 +2516,7 @@ class MGXSLibrary:
# Create and write to the HDF5 file
file = h5py.File(filename, "w", libver=libver)
file.attrs['filetype'] = np.string_(_FILETYPE_MGXS_LIBRARY)
file.attrs['filetype'] = np.bytes_(_FILETYPE_MGXS_LIBRARY)
file.attrs['version'] = [_VERSION_MGXS_LIBRARY, 0]
file.attrs['energy_groups'] = self.energy_groups.num_groups
file.attrs['delayed_groups'] = self.num_delayed_groups

View file

@ -465,11 +465,11 @@ class PlotBase(IDManagerMixin):
domains = geometry.get_all_cells().values()
# Set the seed for the random number generator
np.random.seed(seed)
rng = np.random.RandomState(seed)
# Generate random colors for each feature
for domain in domains:
self.colors[domain] = np.random.randint(0, 256, (3,))
self.colors[domain] = rng.randint(0, 256, (3,))
def to_xml_element(self):
"""Save common plot attributes to XML element

View file

@ -883,7 +883,7 @@ def write_source_file(
# Write array to file
kwargs.setdefault('mode', 'w')
with h5py.File(filename, **kwargs) as fh:
fh.attrs['filetype'] = np.string_("source")
fh.attrs['filetype'] = np.bytes_("source")
fh.create_dataset('source_bank', data=arr, dtype=source_dtype)

View file

@ -10,6 +10,7 @@ from warnings import warn
import lxml.etree as ET
import numpy as np
from scipy.integrate import trapezoid
import openmc.checkvalue as cv
from .._xml import get_text
@ -155,9 +156,9 @@ class Discrete(Univariate):
return np.insert(np.cumsum(self.p), 0, 0.0)
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
rng = np.random.RandomState(seed)
p = self.p / self.p.sum()
return np.random.choice(self.x, n_samples, p=p)
return rng.choice(self.x, n_samples, p=p)
def normalize(self):
"""Normalize the probabilities stored on the distribution"""
@ -363,8 +364,8 @@ class Uniform(Univariate):
return t
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
return np.random.uniform(self.a, self.b, n_samples)
rng = np.random.RandomState(seed)
return rng.uniform(self.a, self.b, n_samples)
def to_xml_element(self, element_name: str):
"""Return XML representation of the uniform distribution
@ -468,8 +469,8 @@ class PowerLaw(Univariate):
self._n = n
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
xi = np.random.rand(n_samples)
rng = np.random.RandomState(seed)
xi = rng.random(n_samples)
pwr = self.n + 1
offset = self.a**pwr
span = self.b**pwr - offset
@ -549,12 +550,14 @@ class Maxwell(Univariate):
self._theta = theta
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
return self.sample_maxwell(self.theta, n_samples)
rng = np.random.RandomState(seed)
return self.sample_maxwell(self.theta, n_samples, rng=rng)
@staticmethod
def sample_maxwell(t, n_samples: int):
r1, r2, r3 = np.random.rand(3, n_samples)
def sample_maxwell(t, n_samples: int, rng=None):
if rng is None:
rng = np.random.default_rng()
r1, r2, r3 = rng.random((3, n_samples))
c = np.cos(0.5 * np.pi * r3)
return -t * (np.log(r1) + np.log(r2) * c * c)
@ -647,9 +650,9 @@ class Watt(Univariate):
self._b = b
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
w = Maxwell.sample_maxwell(self.a, n_samples)
u = np.random.uniform(-1., 1., n_samples)
rng = np.random.RandomState(seed)
w = Maxwell.sample_maxwell(self.a, n_samples, rng=rng)
u = rng.uniform(-1., 1., n_samples)
aab = self.a * self.a * self.b
return w + 0.25*aab + u*np.sqrt(aab*w)
@ -740,8 +743,8 @@ class Normal(Univariate):
self._std_dev = std_dev
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
return np.random.normal(self.mean_value, self.std_dev, n_samples)
rng = np.random.RandomState(seed)
return rng.normal(self.mean_value, self.std_dev, n_samples)
def to_xml_element(self, element_name: str):
"""Return XML representation of the Normal distribution
@ -952,8 +955,8 @@ class Tabular(Univariate):
self.p /= self.cdf().max()
def sample(self, n_samples: int = 1, seed: typing.Optional[int] = None):
np.random.seed(seed)
xi = np.random.rand(n_samples)
rng = np.random.RandomState(seed)
xi = rng.random(n_samples)
# always use normalized probabilities when sampling
cdf = self.cdf()
@ -1069,7 +1072,7 @@ class Tabular(Univariate):
if self.interpolation == 'histogram':
return np.sum(np.diff(self.x) * self.p[:-1])
elif self.interpolation == 'linear-linear':
return np.trapz(self.p, self.x)
return trapezoid(self.p, self.x)
else:
raise NotImplementedError(
f'integral() not supported for {self.inteprolation} interpolation')
@ -1185,7 +1188,7 @@ class Mixture(Univariate):
return np.insert(np.cumsum(self.probability), 0, 0.0)
def sample(self, n_samples=1, seed=None):
np.random.seed(seed)
rng = np.random.RandomState(seed)
# Get probability of each distribution accounting for its intensity
p = np.array([prob*dist.integral() for prob, dist in
@ -1193,8 +1196,7 @@ class Mixture(Univariate):
p /= p.sum()
# Sample from the distributions
idx = np.random.choice(range(len(self.distribution)),
n_samples, p=p)
idx = rng.choice(range(len(self.distribution)), n_samples, p=p)
# Draw samples from the distributions sampled above
out = np.empty_like(idx, dtype=float)

View file

@ -40,7 +40,7 @@ def test_results_save(run_in_tmpdir):
stages = 3
np.random.seed(comm.rank)
rng = np.random.RandomState(comm.rank)
# Mock geometry
op = MagicMock()
@ -68,26 +68,26 @@ def test_results_save(run_in_tmpdir):
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)])
x1.append([rng.random(2), rng.random(2)])
x2.append([rng.random(2), rng.random(2)])
# Construct r
r1 = ReactionRates(burn_list, ["na", "nb"], ["ra", "rb"])
r1[:] = np.random.rand(2, 2, 2)
r1[:] = rng.random((2, 2, 2))
rate1 = []
rate2 = []
for i in range(stages):
rate1.append(copy.deepcopy(r1))
r1[:] = np.random.rand(2, 2, 2)
r1[:] = rng.random((2, 2, 2))
rate2.append(copy.deepcopy(r1))
r1[:] = np.random.rand(2, 2, 2)
r1[:] = rng.random((2, 2, 2))
# Create global terms
# Col 0: eig, Col 1: uncertainty
eigvl1 = np.random.rand(stages, 2)
eigvl2 = np.random.rand(stages, 2)
eigvl1 = rng.random((stages, 2))
eigvl2 = rng.random((stages, 2))
eigvl1 = comm.bcast(eigvl1, root=0)
eigvl2 = comm.bcast(eigvl2, root=0)

View file

@ -78,7 +78,7 @@ def test_wrong_source_attributes(run_in_tmpdir):
])
arr = np.array([(1.0, 2.0, 3), (4.0, 5.0, 6), (7.0, 8.0, 9)], dtype=source_dtype)
with h5py.File('animal_source.h5', 'w') as fh:
fh.attrs['filetype'] = np.string_("source")
fh.attrs['filetype'] = np.bytes_("source")
fh.create_dataset('source_bank', data=arr)
# Create a simple model that uses this lovely animal source

View file

@ -4,6 +4,7 @@ import numpy as np
import pytest
import openmc
import openmc.stats
from scipy.integrate import trapezoid
def assert_sample_mean(samples, expected_mean):
@ -226,7 +227,7 @@ def test_legendre():
# Integrating distribution should yield one
mu = np.linspace(-1., 1., 1000)
assert np.trapz(d(mu), mu) == pytest.approx(1.0, rel=1e-4)
assert trapezoid(d(mu), mu) == pytest.approx(1.0, rel=1e-4)
with pytest.raises(NotImplementedError):
d.to_xml_element('distribution')