gpt4 book ai didi

python - 在 Drake 中,如何将 NumPy 数组转换为不同的标量类型? (例如,从 float 到 AutoDiffXd 或 Expression?)

转载 作者:行者123 更新时间:2023-12-04 03:24:18 28 4
gpt4 key购买 nike

在 Drake 中,我有 dtype=float 的 NumPy ndarray(一些多维),我想将它们转换为 AutoDiffXd表达式

在 C++ 中,我知道我可以做这样的事情:

MatrixXd X(2, 2);
X <<
1.0, 2.0,
3.0, 4.0;
MatrixX<AutoDiffXd> X_ad = X.cast<AutoDiffXd>();

但是,在 Python 中,我发现自己编写了这样的循环:

import numpy as np

from pydrake.autodiffutils import AutoDiffXd

X = np.array([
[1.0, 2.0],
[3.0, 4.0],
])

X_ad = np.zeros(X.shape, dtype=object)
for i in X.shape[0]:
for j in X.shape[1]:
X_ad[i, j] = AutoDiffXd(X[i, j])

有更好的方法吗?

最佳答案

您可以使用 np.vectorize缩短和概括您的代码:
https://numpy.org/doc/1.13/reference/generated/numpy.vectorize.html

例如:

to_autodiff = np.vectorize(AutoDiffXd)
X_ad = to_autodiff(X)

如果您需要更复杂的逻辑,您始终可以自定义您的函数并使用装饰器:

@np.vectorize
def maybe_to_autodiff(x):
if isinstance(x, float):
return AutoDiffXd(x)
else:
return x

X_ad = maybe_to_autodiff(X)

这是与 Eigen 的 .cast<T>() 的(更灵活的)模拟方法(参见“基本矩阵操作”,包含“赋值/复制”的行):
https://eigen.tuxfamily.org/dox/group__QuickRefPage.html

关于python - 在 Drake 中,如何将 NumPy 数组转换为不同的标量类型? (例如,从 float 到 AutoDiffXd 或 Expression?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67892179/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com