首页 > 解决方案 > 我如何使用“fmi2GetDirectionalDerivative”?

问题描述

我正在尝试从 FMU 获取模型 Jacobian 矩阵,根据以下文献,我可以使用它fmi2GetDirectionalDerivative来执行此操作,但我不确定我需要做什么。

我的问题是:

  1. 我可以在 Dymola 或 MATLAB 中调用这个函数吗?
  2. 屏幕截图或示例将非常有帮助。

https://ep.liu.se/ecp/132/091/ecp17132831.pdf

在此处输入图像描述

标签: modelicadymolafmi

解决方案


我不熟悉在 MATLAB 中调用 DLL 函数,但这是 Python 中的一个示例。FMPy ( https://github.com/CATIA-Systems/FMPy ) 有这些用于在 python 中运行 FMU 的包装器。

我已经针对我在这里编写的一个简单模型对此进行了测试(如何在没有分析雅可比的情况下从 FMU 或 Dymola 访问模型雅可比)。在这种情况下,已知是状态或输入的值引用,未知数是导数或输出的值引用。

当通过 Dymola 作为模型交换 FMU 而不是 Co-Simulation FMU 导出时,我已经成功提取了雅可比行列式。

def get_jacobian(fmu, vr_knowns, vr_unknowns):
    """
    populates jacobian from list of knowns and unknowns
    can be only called after the current sim time and inputs are set
    """
    jacobian = []
    try:
        for vr_known in vr_knowns:
            for vr_unknown in vr_unknowns:
                jacobian.extend(
                    fmu.getDirectionalDerivative(
                        vUnknown_ref=[vr_unknown],
                        vKnown_ref=[vr_known],
                        dvKnown=[1.0]
                    ))
        print_status(f'Jacobian Elements: {jacobian}')
    except Exception as e:
        print("[ERROR] cannot compute jacobian at current timestep")
        print(f"[ERROR] {e}")

我使用这个代码片段来收集使用 FMPy 的状态和导数的值引用:

# get FMU model description object
model_description = fmpy.read_model_description(
    os.path.join(fmu_path, fmu_filename)
)

# collect the value references
vrs = {}
for variable in model_description.modelVariables:
    vrs[variable.name] = variable.valueReference

# collect list of states and derivatives
states = []
derivatives = []
for derivative in model_description.derivatives:
    derivatives.append(derivative.variable.name)
    states.append(re.findall('^der\((.*)\)$',derivative.variable.name)[0])

# collect the value references for states and derivatives
vr_states = [vrs[x] for x in states]
vr_derivatives = [vrs[x] for x in derivatives]

推荐阅读