根据概率密度函数p(x,y,z)随机填充3D网格

时间:2015-09-22 19:55:37

标签: python sorting numpy random probability

如何按给定概率密度函数指定的顺序填充3D网格?

使用python,我想按随机顺序放置点,但是根据该区域的某些指定概率分布,没有重复的点。

顺序地:

  • 创建离散的3D网格
  • 为每个网格点指定概率密度函数,pdf(x,y,z)
  • 放下一个点(x0,y0,z0),其随机位置与pdf(x,y,z)成正比
  • 继续添加积分(不重复),直到所有地点都填满

所需的结果是网格中所有点的所有点(无重复)的列表,以便它们被填充。

2 个答案:

答案 0 :(得分:2)

下面没有实现多变量高斯绘图:

xi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())
yi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())
zi_sorted = np.random.choice(x_grid.ravel(),x_grid.ravel().shape, replace=False, p = pdf.ravel())

这是因为p(x)*p(y)*p(z) != p(x,y,z),除非三个变量是独立的。你可以考虑通过从单变量分布中顺序绘制来从联合分布中绘制像Gibbs sampler这样的东西。

在多变量法线的特定情况下,您可以使用(完整示例)

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
from math import *

num_points = 4000

sigma = .5;
mean = [0, 0, 0]
cov = [[sigma**2,0,0],[0,sigma**2,0],[0,0,sigma**2]]

x,y,z = np.random.multivariate_normal(mean,cov,num_points).T

svals = 16
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d',aspect='equal')
ax.scatter(x,y,z, s=svals, alpha=.1,cmap=cm.gray)

答案 1 :(得分:1)

这是一个例子,使用高斯pdf(见图)。此代码很容易适应任何指定的pdf:

%matplotlib qt 
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#number of points to lay down:
n = 4000;

#create meshgrid:
min, max, L = -5, 5, 91;
[x_grid,y_grid,z_grid] = np.meshgrid(np.linspace(min,max,L),np.linspace(min,max,L),np.linspace(min,max,L))
xi,yi,zi = x_grid.ravel(),y_grid.ravel(),z_grid.ravel()

#create normalized pdf (gaussian here):
pdf = np.exp(-(x_grid**2 + y_grid**2 + z_grid**2));
pdf = pdf/np.sum(pdf);

#obtain indices of randomly selected points, as specified by pdf:
randices = np.random.choice(np.arange(x_grid.ravel().shape[0]), n, replace = False,p = pdf.ravel())

#random positions:
x_rand = xi[randices]
y_rand = yi[randices]
z_rand = zi[randices]

fig = plt.figure();
ax = fig.add_subplot(111, projection='3d',aspect='equal')
svals = 16;
ax.scatter(x_rand, y_rand, z_rand, s=svals, alpha=.1)

scatter plot generated by code