Перепроектирование полярного к декартовой сетке

У меня есть полярное (r, тета) сетка (что означает, что каждая ячейка является разделом кольца), содержащий значения некоторого физического количества (например, температура), и я хотел бы к пересетке (или перепроект или передискретизировал бы), эти значения на декартову сетку. Есть ли какие-либо пакеты Python, которые могут сделать это?

Я не интересуюсь преобразованием координат центров ячеек от полярного до последователя Декарта - это очень легко. Вместо этого я ищу пакет, который может на самом деле пересетка данные правильно.

Спасибо за любые предложения!

17
задан AGN Gazer 19 January 2018 в 21:59
поделиться

2 ответа

Спасибо за ваши ответы - после того, как подумал немного об этом, я придумал следующий код:

import numpy as np

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl

from scipy.interpolate import interp1d
from scipy.ndimage import map_coordinates


def polar2cartesian(r, t, grid, x, y, order=3):

    X, Y = np.meshgrid(x, y)

    new_r = np.sqrt(X*X+Y*Y)
    new_t = np.arctan2(X, Y)

    ir = interp1d(r, np.arange(len(r)), bounds_error=False)
    it = interp1d(t, np.arange(len(t)))

    new_ir = ir(new_r.ravel())
    new_it = it(new_t.ravel())

    new_ir[new_r.ravel() > r.max()] = len(r)-1
    new_ir[new_r.ravel() < r.min()] = 0

    return map_coordinates(grid, np.array([new_ir, new_it]),
                            order=order).reshape(new_r.shape)

# Define original polar grid

nr = 10
nt = 10

r = np.linspace(1, 100, nr)
t = np.linspace(0., np.pi, nt)
z = np.random.random((nr, nt))

# Define new cartesian grid

nx = 100
ny = 200

x = np.linspace(0., 100., nx)
y = np.linspace(-100., 100., ny)

# Interpolate polar grid to cartesian grid (nearest neighbor)

fig = mpl.figure()
ax = fig.add_subplot(111)
ax.imshow(polar2cartesian(r, t, z, x, y, order=0), interpolation='nearest')
fig.savefig('test1.png')

# Interpolate polar grid to cartesian grid (cubic spline)

fig = mpl.figure()
ax = fig.add_subplot(111)
ax.imshow(polar2cartesian(r, t, z, x, y, order=3), interpolation='nearest')
fig.savefig('test2.png')

, который не является строго повторно возобновлением, но работает нормально для того, что мне нужно. Просто публиковать код на случай, если это полезно для кого-либо еще. Не стесняйтесь предложить улучшения!

8
ответ дан 30 November 2019 в 14:17
поделиться

Вы можете сделать это более компактно с помощью scipy.ndimage.geometric_transform. Вот пример кода:

import numpy as N
import scipy as S
import scipy.ndimage

temperature = <whatever> 
# This is the data in your polar grid.
# The 0th and 1st axes correspond to r and θ, respectively.
# For the sake of simplicity, θ goes from 0 to 2π, 
# and r's units are just its indices.

def polar2cartesian(outcoords, inputshape, origin):
    """Coordinate transform for converting a polar array to Cartesian coordinates. 
    inputshape is a tuple containing the shape of the polar array. origin is a
    tuple containing the x and y indices of where the origin should be in the
    output array."""

    xindex, yindex = outcoords
    x0, y0 = origin
    x = xindex - x0
    y = yindex - y0

    r = N.sqrt(x**2 + y**2)
    theta = N.arctan2(y, x)
    theta_index = N.round((theta + N.pi) * inputshape[1] / (2 * N.pi))

    return (r,theta_index)

temperature_cartesian = S.ndimage.geometric_transform(temperature, polar2cartesian, 
    order=0,
    output_shape = (temperature.shape[0] * 2, temperature.shape[0] * 2),
    extra_keywords = {'inputshape':temperature.shape,
        'center':(temperature.shape[0], temperature.shape[0])})

Вы можете изменить order=0 по желанию для лучшей интерполяции. Выходной массив temperature_cartesian здесь 2r на 2r, но вы можете указать любой размер и начало координат.

3
ответ дан 30 November 2019 в 14:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: