从落在正方形内的坐标中随机采样点
Randomly sample points from coordinates that fall within a square
我有一个单独的 id 数组和一个单独的数组,它们在 20x20 平面上具有相应的空间坐标。我可以轻松地 select 来自飞机特定部分的个人,如下所示:
from numpy.random import randint
from numpy.random import default_rng
rng = default_rng()
inds = rng.choice(50, size=50, replace=False) #individual tags
locs = np.random.randint(0, 20, size=(50, 2)) #corresponding locations
groups = {
'left' : inds[np.logical_and(locs[:, 0] < 10, locs[:, 1] < 20)],
'right' : inds[np.logical_and(locs[:, 0] > 10, locs[:, 1] > 0)]
}
这给了我一个“左”和“右”组。但是,我想随机将一个 4x4 大小的正方形放到平面上,并仅对落在该正方形内的个体进行采样。任何帮助将不胜感激!
您可以使用 numpy.clip
和矩形坐标,然后检查裁剪后的坐标是否与原始坐标相同(如果是,则裁剪没有做任何事情,这意味着坐标已经在矩形内):
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
rng = np.random.default_rng(seed=0)
locs = rng.integers(0, 20, size=(250, 2))
rect_size = np.array([4, 4])
rect_bot_left = rng.integers(0, 20-rect_size, size=2)
rect_top_right = rect_bot_left + rect_size
inside = (locs == np.clip(locs, rect_bot_left, rect_top_right)).all(axis=1)
fig, ax = plt.subplots(figsize=(6, 6))
ax.scatter(*locs.T, c=inside)
ax.add_patch(Rectangle(rect_bot_left, *rect_size, edgecolor='red', facecolor='none'))
plt.show()
我有一个单独的 id 数组和一个单独的数组,它们在 20x20 平面上具有相应的空间坐标。我可以轻松地 select 来自飞机特定部分的个人,如下所示:
from numpy.random import randint
from numpy.random import default_rng
rng = default_rng()
inds = rng.choice(50, size=50, replace=False) #individual tags
locs = np.random.randint(0, 20, size=(50, 2)) #corresponding locations
groups = {
'left' : inds[np.logical_and(locs[:, 0] < 10, locs[:, 1] < 20)],
'right' : inds[np.logical_and(locs[:, 0] > 10, locs[:, 1] > 0)]
}
这给了我一个“左”和“右”组。但是,我想随机将一个 4x4 大小的正方形放到平面上,并仅对落在该正方形内的个体进行采样。任何帮助将不胜感激!
您可以使用 numpy.clip
和矩形坐标,然后检查裁剪后的坐标是否与原始坐标相同(如果是,则裁剪没有做任何事情,这意味着坐标已经在矩形内):
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
rng = np.random.default_rng(seed=0)
locs = rng.integers(0, 20, size=(250, 2))
rect_size = np.array([4, 4])
rect_bot_left = rng.integers(0, 20-rect_size, size=2)
rect_top_right = rect_bot_left + rect_size
inside = (locs == np.clip(locs, rect_bot_left, rect_top_right)).all(axis=1)
fig, ax = plt.subplots(figsize=(6, 6))
ax.scatter(*locs.T, c=inside)
ax.add_patch(Rectangle(rect_bot_left, *rect_size, edgecolor='red', facecolor='none'))
plt.show()