Python
以下是一阶伴随模式的使用示例:
import xad.adj_1st as xadj
# set independent variables
x0_ad = xadj.Real(1.0)
x1_ad = xadj.Real(1.5)
x2_ad = xadj.Real(1.3)
x3_ad = xadj.Real(1.2)
with xadj.Tape() as tape:
# and register them
tape.registerInput(x0_ad)
tape.registerInput(x1_ad)
tape.registerInput(x2_ad)
tape.registerInput(x3_ad)
# start recording derivatives
tape.newRecording()
# calculate the output
y = x0_ad + x1_ad - x2_ad * x3_ad
# register and seed adjoint of output
tape.registerOutput(y)
y.derivative = 1.0
# compute all other adjoints
tape.computeAdjoints()
# output results
print(f"y = {y}")
print(f"first order derivatives:\n")
print(f"dy/dx0 = {x0_ad.derivative}")
print(f"dy/dx1 = {x1_ad.derivative}")
print(f"dy/dx2 = {x2_ad.derivative}")
print(f"dy/dx3 = {x3_ad.derivative}")
Python绑定在语法和工作流程上基本与C++版本保持一致。
模块与命名
| 模块 | 描述 | 内容 |
|---|---|---|
xad | The main module, which contain global functions and subpackages | value, derivative |
xad.exceptions | Contains all exceptions, with the same names as described in Exceptions | e.g. NoTapeException |
xad.math | Mirrors Python's math module, with functions for XAD's active types. | e.g. sin, exp |
xad.fwd_1st | Active type for first-order forward mode | Real |
xad.adj_1st | Active type for first-order adjoint mode as well as the corresponding tape type | Real, Tape |
注意事项
- 支持一阶前向模式(模块
xad.fwd_1st)和一阶伴随模式(模块xad.adj_1st) - 在所有模式下,活动类型都称为
Real - 在伴随模式中,新构建的
Tape对象在构造时不会自动激活。可以通过tape.activate()稍后激活,但我们建议像上面示例中那样使用with代码块。 xad.math中的数学函数被设计为标准Pythonmath模块的即插即用替代品。它们不仅支持使用XAD的主动类型调用,也支持常规float变量的调用。- Python版本目前暂不支持检查点功能和外部函数特性。
- 活跃类型的
x.getDerivative()和x.setDerivative()方法也可通过Python属性x.derivative使用,同时具备设置和获取功能。 - 主动类型的
x.getValue()方法也可以通过只读属性x.value访问 - 使用
y.setDerivative(1.0)或属性设置器y.derivative = 1.0来设置初始导数并访问导数。 - Python绑定目前尚不支持复数运算。