Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MAINT: Move to new numpy.random API in test_*.py #16086

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 0 additions & 3 deletions .ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,6 @@ lint.ignore = [
"N816", # mixed-case-variable-in-global-scope
"N818", # error-suffix-on-exception-name

# NumPy-specific rules (NPY)
"NPY002", # Replace legacy `np.random.rand` call with `np.random.Generator` (2023-05-03)

# Perflint (PERF)
"PERF203", # `try`-`except` within a loop incurs performance overhead
"PERF401", # Use a list comprehension to create a transformed list
Expand Down
9 changes: 4 additions & 5 deletions astropy/convolution/tests/test_convolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -1171,15 +1171,14 @@ def test_asymmetric_kernel(boundary):

@pytest.mark.parametrize("ndims", (1, 2, 3))
def test_convolution_consistency(ndims):
np.random.seed(0)
array = np.random.randn(*([3] * ndims))
np.random.seed(0)
kernel = np.random.rand(*([3] * ndims))
rng = np.random.default_rng(0)
array = rng.standard_normal([3] * ndims)
kernel = rng.random([3] * ndims)

conv_f = convolve_fft(array, kernel, boundary="fill")
conv_d = convolve(array, kernel, boundary="fill")

assert_array_almost_equal_nulp(conv_f, conv_d, 30)
assert_array_almost_equal_nulp(conv_f, conv_d, 40)


def test_astropy_convolution_against_numpy():
Expand Down
3 changes: 2 additions & 1 deletion astropy/convolution/tests/test_convolve_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ def test_random_makekernel(self, kernel):

shape = kernel.array.shape

x = np.random.randn(*shape)
rng = np.random.default_rng()
x = rng.standard_normal(shape)

c2 = convolve_fft(x, kernel, boundary="fill")
c1 = convolve(x, kernel, boundary="fill")
Expand Down
5 changes: 2 additions & 3 deletions astropy/convolution/tests/test_convolve_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from astropy.convolution.convolve import convolve, convolve_fft, convolve_models
from astropy.modeling import fitting, models
from astropy.utils.compat.optional_deps import HAS_SCIPY
from astropy.utils.misc import NumpyRNGContext


class TestConvolve1DModels:
Expand Down Expand Up @@ -87,8 +86,8 @@ def test_fitting_convolve_models(self, mode):

x = np.linspace(-5, 5, 99)
fake_model = models.Gaussian1D(amplitude=10)
with NumpyRNGContext(123):
fake_data = fake_model(x) + np.random.normal(size=len(x))
rng = np.random.default_rng(0)
fake_data = fake_model(x) + rng.normal(size=len(x))

init_model = convolve_models(b1, g1, mode=mode, normalize_kernel=False)
fitter = fitting.LevMarLSQFitter()
Expand Down
5 changes: 3 additions & 2 deletions astropy/convolution/tests/test_kernel_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@
delta_pulse_2D = np.zeros((81, 81))
delta_pulse_2D[40, 40] = 1

random_data_1D = np.random.rand(61)
random_data_2D = np.random.rand(61, 61)
rng = np.random.default_rng()
random_data_1D = rng.random(61)
random_data_2D = rng.random((61, 61))


class TestKernels:
Expand Down
4 changes: 3 additions & 1 deletion astropy/convolution/tests/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
from astropy import convolution as conv
from astropy.tests.helper import check_pickling_recovery, pickle_protocol # noqa: F401

rng = np.random.default_rng()


@pytest.mark.parametrize(
("name", "args", "kwargs", "xfail"),
[
(conv.CustomKernel, [], {"array": np.random.rand(15)}, False),
(conv.CustomKernel, [], {"array": rng.random(15)}, False),
(conv.Gaussian1DKernel, [1.0], {"x_size": 5}, True),
(conv.Gaussian2DKernel, [1.0], {"x_size": 5, "y_size": 5}, True),
],
Expand Down
41 changes: 20 additions & 21 deletions astropy/coordinates/tests/accuracy/generate_ref_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@ def ref_fk4_no_e_fk4(fnout="fk4_no_e_fk4.csv"):
"""
import starlink.Ast as Ast

np.random.seed(12345)
rng = np.random.default_rng(12345)

N = 200

# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(np.random.uniform(-1.0, 1.0, N)))
ra = rng.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(rng.uniform(-1.0, 1.0, N)))

# Generate random observation epoch and equinoxes
obstime = [f"B{x:7.2f}" for x in np.random.uniform(1950.0, 2000.0, N)]
obstime = [f"B{x:7.2f}" for x in rng.uniform(1950.0, 2000.0, N)]

ra_fk4ne, dec_fk4ne = [], []
ra_fk4, dec_fk4 = [], []
Expand Down Expand Up @@ -75,20 +75,20 @@ def ref_fk4_no_e_fk5(fnout="fk4_no_e_fk5.csv"):
"""
import starlink.Ast as Ast

np.random.seed(12345)
rng = np.random.default_rng(12345)

N = 200

# Sample uniformly on the unit sphere. These will be either the FK4
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to FK4.
ra = np.random.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(np.random.uniform(-1.0, 1.0, N)))
ra = rng.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(rng.uniform(-1.0, 1.0, N)))

# Generate random observation epoch and equinoxes
obstime = [f"B{x:7.2f}" for x in np.random.uniform(1950.0, 2000.0, N)]
equinox_fk4 = [f"B{x:7.2f}" for x in np.random.uniform(1925.0, 1975.0, N)]
equinox_fk5 = [f"J{x:7.2f}" for x in np.random.uniform(1975.0, 2025.0, N)]
obstime = [f"B{x:7.2f}" for x in rng.uniform(1950.0, 2000.0, N)]
equinox_fk4 = [f"B{x:7.2f}" for x in rng.uniform(1925.0, 1975.0, N)]
equinox_fk5 = [f"J{x:7.2f}" for x in rng.uniform(1975.0, 2025.0, N)]

ra_fk4, dec_fk4 = [], []
ra_fk5, dec_fk5 = [], []
Expand Down Expand Up @@ -140,19 +140,19 @@ def ref_galactic_fk4(fnout="galactic_fk4.csv"):
"""
import starlink.Ast as Ast

np.random.seed(12345)
rng = np.random.default_rng(12345)

N = 200

# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
lon = np.random.uniform(0.0, 360.0, N)
lat = np.degrees(np.arcsin(np.random.uniform(-1.0, 1.0, N)))
lon = rng.uniform(0.0, 360.0, N)
lat = np.degrees(np.arcsin(rng.uniform(-1.0, 1.0, N)))

# Generate random observation epoch and equinoxes
obstime = [f"B{x:7.2f}" for x in np.random.uniform(1950.0, 2000.0, N)]
equinox_fk4 = [f"J{x:7.2f}" for x in np.random.uniform(1975.0, 2025.0, N)]
obstime = [f"B{x:7.2f}" for x in rng.uniform(1950.0, 2000.0, N)]
equinox_fk4 = [f"J{x:7.2f}" for x in rng.uniform(1975.0, 2025.0, N)]

lon_gal, lat_gal = [], []
ra_fk4, dec_fk4 = [], []
Expand Down Expand Up @@ -201,19 +201,18 @@ def ref_icrs_fk5(fnout="icrs_fk5.csv"):
"""
import starlink.Ast as Ast

np.random.seed(12345)

rng = np.random.default_rng(12345)
N = 200

# Sample uniformly on the unit sphere. These will be either the ICRS
# coordinates for the transformation to FK5, or the FK5 coordinates for the
# transformation to ICRS.
ra = np.random.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(np.random.uniform(-1.0, 1.0, N)))
ra = rng.uniform(0.0, 360.0, N)
dec = np.degrees(np.arcsin(rng.uniform(-1.0, 1.0, N)))

# Generate random observation epoch and equinoxes
obstime = [f"B{x:7.2f}" for x in np.random.uniform(1950.0, 2000.0, N)]
equinox_fk5 = [f"J{x:7.2f}" for x in np.random.uniform(1975.0, 2025.0, N)]
obstime = [f"B{x:7.2f}" for x in rng.uniform(1950.0, 2000.0, N)]
equinox_fk5 = [f"J{x:7.2f}" for x in rng.uniform(1975.0, 2025.0, N)]

ra_icrs, dec_icrs = [], []
ra_fk5, dec_fk5 = [], []
Expand Down
12 changes: 6 additions & 6 deletions astropy/coordinates/tests/accuracy/generate_spectralcoord_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,21 @@
from astropy.table import QTable
from astropy.time import Time

np.random.seed(12345)
rng = np.random.default_rng(12345)

N = 100

tab = QTable()
target_lon = np.random.uniform(0, 360, N) * u.deg
target_lat = np.degrees(np.arcsin(np.random.uniform(-1, 1, N))) * u.deg
target_lon = rng.uniform(0, 360, N) * u.deg
target_lat = np.degrees(np.arcsin(rng.uniform(-1, 1, N))) * u.deg
tab["target"] = SkyCoord(target_lon, target_lat, frame="fk5")
tab["obstime"] = Time(
np.random.uniform(Time("1997-01-01").mjd, Time("2017-12-31").mjd, N),
rng.uniform(Time("1997-01-01").mjd, Time("2017-12-31").mjd, N),
format="mjd",
scale="utc",
)
tab["obslon"] = Angle(np.random.uniform(-180, 180, N) * u.deg)
tab["obslat"] = Angle(np.arcsin(np.random.uniform(-1, 1, N)) * u.deg)
tab["obslon"] = Angle(rng.uniform(-180, 180, N) * u.deg)
tab["obslat"] = Angle(np.arcsin(rng.uniform(-1, 1, N)) * u.deg)
tab["geocent"] = 0.0
tab["heliocent"] = 0.0
tab["lsrk"] = 0.0
Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/accuracy/test_fk4_no_e_fk4.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def test_fk4_no_e_fk4():
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
idxs = np.random.default_rng().integers(len(t), size=N_ACCURACY_TESTS)

diffarcsec1 = []
diffarcsec2 = []
Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/accuracy/test_fk4_no_e_fk5.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_fk4_no_e_fk5():
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
idxs = np.random.default_rng().integers(len(t), size=N_ACCURACY_TESTS)

diffarcsec1 = []
diffarcsec2 = []
Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/accuracy/test_galactic_fk4.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_galactic_fk4():
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
idxs = np.random.default_rng().integers(len(t), size=N_ACCURACY_TESTS)

diffarcsec1 = []
diffarcsec2 = []
Expand Down
2 changes: 1 addition & 1 deletion astropy/coordinates/tests/accuracy/test_icrs_fk5.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_icrs_fk5():
if N_ACCURACY_TESTS >= len(t):
idxs = range(len(t))
else:
idxs = np.random.randint(len(t), size=N_ACCURACY_TESTS)
idxs = np.random.default_rng().integers(len(t), size=N_ACCURACY_TESTS)

diffarcsec1 = []
diffarcsec2 = []
Expand Down
11 changes: 6 additions & 5 deletions astropy/coordinates/tests/test_api_ape5.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,22 +124,23 @@ def test_representations_api():
# physics convention, as it is one of the most common cases.
_ = PhysicsSphericalRepresentation(phi=120 * u.deg, theta=85 * u.deg, r=3 * u.kpc)

rng = np.random.default_rng()
# first dimension must be length-3 if a lone `Quantity` is passed in.
c1 = CartesianRepresentation(np.random.randn(3, 100) * u.kpc)
c1 = CartesianRepresentation(rng.standard_normal((3, 100)) * u.kpc)
assert c1.xyz.shape[0] == 3
assert c1.xyz.unit == u.kpc
assert c1.x.shape[0] == 100
assert c1.y.shape[0] == 100
assert c1.z.shape[0] == 100
# can also give each as separate keywords
CartesianRepresentation(
x=np.random.randn(100) * u.kpc,
y=np.random.randn(100) * u.kpc,
z=np.random.randn(100) * u.kpc,
x=rng.standard_normal(100) * u.kpc,
y=rng.standard_normal(100) * u.kpc,
z=rng.standard_normal(100) * u.kpc,
)
# if the units don't match but are all distances, they will automatically be
# converted to match `x`
xarr, yarr, zarr = np.random.randn(3, 100)
xarr, yarr, zarr = rng.standard_normal((3, 100))
c1 = CartesianRepresentation(x=xarr * u.kpc, y=yarr * u.kpc, z=zarr * u.kpc)
c2 = CartesianRepresentation(x=xarr * u.kpc, y=yarr * u.kpc, z=zarr * u.pc)
assert c1.xyz.unit == c2.xyz.unit == u.kpc
Expand Down
11 changes: 6 additions & 5 deletions astropy/coordinates/tests/test_frames_with_velocity.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,15 @@ def test_shorthand_attributes():
# Check that attribute access works

# for array data:
rng = np.random.default_rng()
n = 4
icrs1 = ICRS(
ra=np.random.uniform(0, 360, n) * u.deg,
dec=np.random.uniform(-90, 90, n) * u.deg,
ra=rng.uniform(0, 360, n) * u.deg,
dec=rng.uniform(-90, 90, n) * u.deg,
distance=100 * u.pc,
pm_ra_cosdec=np.random.normal(0, 100, n) * u.mas / u.yr,
pm_dec=np.random.normal(0, 100, n) * u.mas / u.yr,
radial_velocity=np.random.normal(0, 100, n) * u.km / u.s,
pm_ra_cosdec=rng.normal(0, 100, n) * u.mas / u.yr,
pm_dec=rng.normal(0, 100, n) * u.mas / u.yr,
radial_velocity=rng.normal(0, 100, n) * u.km / u.s,
)
v = icrs1.velocity
pm = icrs1.proper_motion
Expand Down
19 changes: 9 additions & 10 deletions astropy/coordinates/tests/test_matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,16 @@ def test_python_kdtree(monkeypatch):
def test_matching_method():
from astropy.coordinates import ICRS, SkyCoord
from astropy.coordinates.matching import match_coordinates_3d, match_coordinates_sky
from astropy.utils import NumpyRNGContext

with NumpyRNGContext(987654321):
cmatch = ICRS(
np.random.rand(20) * 360.0 * u.degree,
(np.random.rand(20) * 180.0 - 90.0) * u.degree,
)
ccatalog = ICRS(
np.random.rand(100) * 360.0 * u.degree,
(np.random.rand(100) * 180.0 - 90.0) * u.degree,
)
rng = np.random.default_rng(987654321)
cmatch = ICRS(
rng.random(20) * 360.0 * u.degree,
(rng.random(20) * 180.0 - 90.0) * u.degree,
)
ccatalog = ICRS(
rng.random(100) * 360.0 * u.degree,
(rng.random(100) * 180.0 - 90.0) * u.degree,
)

idx1, d2d1, d3d1 = SkyCoord(cmatch).match_to_catalog_3d(ccatalog)
idx2, d2d2, d3d2 = match_coordinates_3d(cmatch, ccatalog)
Expand Down
8 changes: 4 additions & 4 deletions astropy/coordinates/tests/test_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,10 +339,10 @@ def test_regression_5209():

def test_regression_5133():
N = 1000
np.random.seed(12345)
lon = np.random.uniform(-10, 10, N) * u.deg
lat = np.random.uniform(50, 52, N) * u.deg
alt = np.random.uniform(0, 10.0, N) * u.km
rng = np.random.default_rng(12345)
lon = rng.uniform(-10, 10, N) * u.deg
lat = rng.uniform(50, 52, N) * u.deg
alt = rng.uniform(0, 10.0, N) * u.km

time = Time("2010-1-1")

Expand Down
3 changes: 2 additions & 1 deletion astropy/coordinates/tests/test_shape_manipulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ def setup_class(cls):
cls.pressure = 1000 * u.hPa
# As well as an array.
cls.temperature = (
np.random.uniform(0.0, 20.0, size=(lon.size, lat.size)) * u.deg_C
np.random.default_rng().uniform(0.0, 20.0, size=(lon.size, lat.size))
* u.deg_C
)
cls.s1 = AltAz(
az=lon[:, np.newaxis],
Expand Down