在when语句中使用reinit() 的算法

编程语言 2026-07-10

我在一个很长的 when-elsewhen 语句中写了一段Modelica代码,该语句使用 reinit() 作为一个连续时间变量,并且在 equation 部分嵌入了 if-elseif。在某些情况下,如果出现特定条件,我会使用下面这段代码来什么也不做,并让变量的赋值与 whenif 部分的其他部分保持一致:

variable = pre(variable) ;

看起来Dymola把我的方程重写成如下形式(我尽量用一种非常简化的方式来再现我正在使用的代码):

condition1 = pre(variable1);
...
conditionN = .... ;
when {condition1, ..., consitionN}  then
    variable1 = if NothingToDoCondition then pre(variable)  else value;
    variable2 = if NothingToDoCondition then pre(variable)  else anotherValue;
    ....
    variableM =... //as above
    if condition then
        reinit(x,y) ;
    else
        //no equation
    end if ;
elsewhen ....
   // repeat as above

end when;

Dymola的检查报告如下:

This elsewhen in equations is not supported, it can be worked around by rewriting as algorithm, however be careful since the right-hand-side is dependent on left-hand-side variables and that is handled differently in algorithms

首先,我不知道如何将我的代码转换成一个 algorithm 部分,因为我使用了 reinit(),而它不能在 algorithm 部分使用。是否有一个替代的 reinit(),可以在 algorithm 部分使用?

其次,如何理解Dymola检查的这条信息?在使用一个 when 语句在 algorithmequation 中会有哪些影响?

解决方案

有一种替代使用算法的方法。

一般来说

equation
  when {condition1, ..., conditionN}  then
    variable1 = if NothingToDoCondition then pre(variable1)  else value11;
    variable2 = if NothingToDoCondition then pre(variable2)  else value12;
    ....
    variableM =... //as above
    if condition then
        reinit(x,y) ;
    else
        //no equation
    end if ;
elsewhen ....
   variable1 = if NothingToDoCondition then pre(variable1)  else value21;
   variable2 = if NothingToDoCondition then pre(variable2)  else value22;
    ....
   variableM =... //as above
end when;

等价于:

equation
  when {condition1, ..., conditionN}  then
    variable1 = if NothingToDoCondition then pre(variable1)  else value11;
  elsewhen ....
    variable1 = if NothingToDoCondition then pre(variable1)  else value21;
  end when;

  when {condition1, ..., conditionN}  then
    variable2 = if NothingToDoCondition then pre(variable2)  else value12;
  elsewhen ....
    variable2 = if NothingToDoCondition then pre(variable2)  else value22;
  end when;

  ...

  when {condition1, ..., conditionN}  then
    variableM = if NothingToDoCondition then pre(variableM)  else value1M;
  elsewhen ....
    variableM = if NothingToDoCondition then pre(variableM)  else value2M;
  end when;

  when {condition1, ..., conditionN}  then
    if condition then
        reinit(x,y) ;
    else
        //no equation
    end if ;
  end when;

或其变体——把重新初始化分离出来可能就足够了。

据我所知,Dymola应该能够自动完成这一步(取决于版本)。不过,如果变量在所有分支中的形式并不完全相同,可能会失败——在这种情况下,单独把重新初始化分离出来很可能就能奏效。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章