【问题标题】:Applying a function to meshgrids only under select polygon criteria?仅在选择多边形标准下将函数应用于网格网格?
【发布时间】:2020-12-19 18:15:18
【问题描述】:

我的问题与这篇文章类似,但我在调整它时遇到了一些问题: Ambiguous truth value for meshgrid and user-defined functions using if-statement

基本上,我不希望条件语句看起来像这样:

import numpy as np

def test(x, y):
    a = 1.0/(1+x*x)
    b = np.ones(y.shape)
    mask = (y!=0)
    b[mask] = np.sin(y[mask])/y[mask]
    return a*b

相反,“掩码”取决于 x,y 是否位于某个多边形内。所以结果数组中的每个值都是 1,但会生成 4 个值之间的多边形。我只希望该函数应用于位于多边形内的 2 个网格输入 (X,Y) 中的点

x 和 y 是实数,可以为负数。

我不确定如何将数组项作为奇异值传递。

我最终想在彩色图上绘制 Z 谢谢

即多边形内的点进行变换,多边形外的点保持为 1 例如,我希望我的函数看起来像这样

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
def f(x, y, poly):
    a = 1.0/(1+x*x)
    b = np.ones(y.shape)
    mask = (Point(x,y).within(poly) == True)
    b[mask] = a*b
    return b 

x 和 y 是任意维度的网格网格

我应该补充一点,我收到以下错误: “只有 size-1 的数组可以转换为 Python 标量”

生成X和Y,调用函数通过

coords = [(0, 0), (4,0), (4,4), (0,4)]
poly = Polygon(coords)
x = np.linspace(0,10, 11, endpoint = True) # x intervals
y = np.linspace(0,10,11, endpoint = True) # y intervals
X, Y = np.meshgrid(x,y)

Z = f(X, Y, poly)

谢谢!

错误信息:

Traceback (most recent call last):
  File "meshgrid_understanding.py", line 28, in <module>
    Z = f(X, Y, poly)
  File "meshgrid_understanding.py", line 16, in f
    mask = (Point(x,y).within(poly) != True)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python37\lib\site-packages\shapely\geometry\point.py", line 48, in __init__
    self._set_coords(*args)
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python37\lib\site-packages\shapely\geometry\point.py", line 137, in _set_coords
    self._geom, self._ndim = geos_point_from_py(tuple(args))
  File "C:\Users\Nick\AppData\Local\Programs\Python\Python37\lib\site-packages\shapely\geometry\point.py", line 214, in geos_point_from_py
    dx = c_double(coords[0])
TypeError: only size-1 arrays can be converted to Python scalars

【问题讨论】:

    标签: python arrays numpy logic shapely


    【解决方案1】:

    Matplotlib 有一个接受点数组的函数。演示:

    import numpy as np
    from matplotlib.path import Path
    
    coords = [(0, 0), (4,0), (4,4), (0,4)]
    
    x = np.linspace(0, 10, 11, endpoint=True)
    y = np.linspace(0, 10, 11, endpoint=True)
    X, Y = np.meshgrid(x, y)
    
    points = np.c_[X.ravel(), Y.ravel()]
    mask = Path(coords).contains_points(points).reshape(X.shape)
    

    【讨论】:

    • 它适用于为 b[mask] 分配值,即 b[mask] = 3,但我似乎无法将值分配为其位置的函数。例如,我希望 b[mask] 中的每个点都是其 x 和 y 坐标的函数。如果我通过 b[mask] = 3x+2y 等操作,我只会得到一个错误
    • 我实际上是通过使用这个解决了它。感谢您的帮助
    【解决方案2】:

    您将数组传递给接受单个值的函数Point

    【讨论】:

    • 这就是重点,我不确定如何提供单个值,一旦函数完成,对应于它们各自的 x,y 对
    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多