【问题标题】:Understanding Mathematica contour lines extraction了解 Mathematica 等高线提取
【发布时间】:2017-12-20 05:05:04
【问题描述】:

我的教授给我发了一本 Mathematica Notebook,他在其中绘制了一个 2d 轮廓,然后将轮廓提取为线条(即坐标元组列表的列表)。具体代码段如下所示:

xdiv = 0.05
zt = 1.
lis = Table[SomeFunction[x, y, zt], {y, -xmax, xmax, xdiv}, {x, -xmax, xmax, xdiv}];
plot = ListContourPlot[lis, PlotLegends -> Automatic, Contours -> {0}, ContourShading -> None];
lines = Cases[Normal@plot, Line[pts_, ___] :> xdiv*pts, Infinity];

我不完全理解代码是如何完成它的工作的,我正在寻求帮助以获得解释。我想在 python 中编写类似的代码并了解如何。另外我想知道是否可以在不使用 ContourPlot 函数的情况下提取线条。我对绘制轮廓不是特别感兴趣,我只需要它的线条列表。

编辑:改写问题。 另外:matplotlib - extracting data from contour lines 似乎解释了如何在 python 中实现我的目标。但是,我并不真正了解 如何 它做了什么,并判断在性能方面是否有更好的方法来实现它(我正在处理非常大的列表,所以这个轮廓提取似乎是一个瓶颈)。我一直在寻找更多的解释来了解到底发生了什么。提供的答案在解释 Mathematica 代码方面做得很好。我将详细了解 matplotlib 方法。

【问题讨论】:

  • 你和你的教授讨论过代码是如何工作的吗?
  • 嗯,是的,但我们都不是计算机科学家,所以他无法解释最后一行使用“案例”的确切作用。
  • @Banana Cases 既是模式匹配函数又是解构函数。最简单的方法是以 Python 的方式解决问题,而不是尝试移植 Mathematica 代码。或者,既然您似乎愿意使用subprocess 来完成工作,请查看Wolfram Script。然后在 Mathematica 端将您找到的行转储为更易于 Python 阅读的格式。
  • @b3m2a1 你有一个pythonic方法来实现这个的想法吗? “转储为更易于 Python 阅读的格式”是什么意思? Wolfram Script 只会运行脚本,不是吗?

标签: python export wolfram-mathematica equivalent


【解决方案1】:

下面是对正在发生的事情的一些解释,并带有一个示例函数:

SomeFunction[x_, y_, zt_] := Sin[3 x + y^2]
xmax = 4;

xdiv = 0.05;
zt = 1.;
lis = Table[SomeFunction[x, y, zt], {y, -xmax, xmax, xdiv}, {x, -xmax, xmax, xdiv}];
plot = ListContourPlot[lis, PlotLegends -> Automatic, Contours -> {0},
  ContourShading -> None];
normalplot = Normal@plot

cases = Cases[normalplot, Line[pts_, ___], Infinity];
Length[cases]
First[cases]
17
Line[{{16.2216, 1.}, {17., 1.29614}, ... , {16.7818, 160.782}, {16.2216, 161.}}]

Cases 语句从标准化图中提取每一行。 (Normal 将图形形式简化为一种适用于Cases 的形式。)Line[List[{x, y}, {x, y}, ...]] 形式有 17 行单独的行。

对于每一行List[{x, y}, {x, y}, ...]pts 表示,所以

lines = Cases[normalplot, Line[pts_, ___] :> xdiv*pts, Infinity]

pts 的每个列表乘以xdiv

0.05 * {{16.2216, 1.}, {17., 1.29614}, ... , {16.7818, 160.782}, {16.2216, 161.}}
= {{0.81108, 0.05}, {0.85, 0.0648069}, ... {0.839088, 8.03909}, {0.81108, 8.05}}

可以绘制线条。

ListLinePlot[lines, AspectRatio -> 1]

【讨论】:

  • 谢谢@chris,这真的很有帮助。你能解释一下 Infinity 关键字的作用是什么吗?我无法从文档中判断。您知道 Contourplot 如何“找到”线条,以及是否有更快的方法直接获取线条列表?我不一定需要情节
  • Infinitylevelspec 值。它指定Line[pts_, ___] 模式应该匹配到表达式的多少级。请参阅Cases 的语法。对于获得轮廓线,我会说ListContourPlot 是理想的方法。该图是偶然的 - 只是计算轮廓的容器 - 不需要显示。
  • 谢谢。我很困惑,因为在文档中似乎 Infinity 无论如何都是默认值,这使得这个 Argument 变得多余。
  • @Banana 我认为没有什么比使用等高线图例程更快的了。您应该访问mathematica.stackexchange.com 了解更多问题。 (先搜索)。
猜你喜欢
  • 2022-08-19
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多