Python:根据函数的值减少网格

问题描述 投票:0回答:1

我有一个规则间隔的网格,比方说200 * 200 * 200 = 8,000,000点。我还有一个函数f的值列表(它取正值和负值,并且在这个网格的每个点上变化很大),如下所示:

import numpy as np
from itertools import product

x = np.linspace(0, 200*0.05, 200)
y = np.linspace(0, 200*0.05, 200)
z = np.linspace(0, 200*0.05, 200)
coordinates = np.array(list(product(x, y, z)))

In [1]: print(coordinates, coordinates.shape)
[[  0.           0.           0.        ]
 [  0.           0.           0.05025126]
 [  0.           0.           0.10050251]
 ..., 
 [ 10.          10.           9.89949749]
 [ 10.          10.           9.94974874]
 [ 10.          10.          10.        ]]
(8000000, 3)

In [2]: print(f,"\n",f.shape)
[  2.46143000e-08   3.01043000e-08   3.64817000e-08 ...,   6.79642000e-08
   5.83957000e-08   4.95127000e-08]
(8000000,)

In [3]: print(np.max(f), np.min(f), np.min(np.absolute(f)))
6.21966 -271.035 1.10296e-09

如何获得一个点数较少(约250,000点)的新网格,这在高f值区域非常精确,而在低f值区域则更不精确?

这个新网格可以是常规的,但也可以更加复杂,只要我之后仍然可以在空间上集成该功能。预先感谢您的帮助 !

编辑:我刚刚发现了scipy.interpolate.griddata函数,如果我找到一个新的网格,即使这个网格不规则,这将非常有用。有没有生成网格的python库?

python optimization grid integration precision
1个回答
0
投票

我最终使用以下代码,受此following stackoverflow question启发,并定义了f的概率密度:

n = 250000
g = 2 #the higher g, the more precise the grid will be in regions of high f, and vice-versa

x = np.linspace(0, 200*0.05, 200)
y = np.linspace(0, 200*0.05, 200)
z = np.linspace(0, 200*0.05, 200)
[x_grid,y_grid,z_grid] = np.meshgrid(x,y,z)
xi,yi,zi = x_grid.ravel(),y_grid.ravel(),z_grid.ravel()

#create normalized pdf
pdf = np.log10(np.absolute(f))
pdf = pdf - pdf.min() + 1
pdf = pdf**g
pdf = pdf/np.sum(pdf)

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

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

#coordinates
grid_coord = np.array([x_rand, y_rand, z_rand]).swapaxes(0,1)
© www.soinside.com 2019 - 2024. All rights reserved.