Можно ли установить тип переменной с помощью параметра в Modelica?

Я разработал модель настраиваемой переменной, что означает, что переменная может быть определена параметром, указана через реальный ввод или оставлена ​​неопределенной, чтобы ее можно было решить.

model ConfigurableReal   

"Configurable variable that can be set by parameter, by real input, or left undetermined"

  parameter Boolean isSpecifiedByParameter = false 
    "true if value is specified by paramter"
    annotation(Dialog(group="Specify by Parameter", enable = not isSpecifiedByInput));

  parameter Boolean isSpecifiedByInput = false 
    "true if value is specified by real input"
    annotation(Dialog(group = "Specify by Real Input", enable=not isSpecifiedByParameter));

  parameter Real specifiedValue(unit=unitString) = 0 
    "specified value to use if isSpecifiedByParameter == true"
    annotation(Dialog(group="Specify by Parameter", enable = isSpecifiedByParameter));

  // Conditionally declare the realInput
  Modelica.Blocks.Interfaces.RealInput realInput if isSpecifiedByInput
    annotation (Placement(transformation(extent={{-140,-20},{-100,20}})));

  Real value "active value";

protected 
  Modelica.Blocks.Sources.Constant constantBlock(final k = specifiedValue) if isSpecifiedByParameter 
    "constant block to hold specified input";

  Modelica.Blocks.Interfaces.RealInput value_ "connected value";

equation 
  value = value_;

  // Connect the real input to the value if the real input exists
  // This only happens if isSpecifiedByInput==true, because the RealInput is
  // conditionally declared above
  connect(realInput, value_);

  // Connect the constant block to the value if the value is specified by parameter
  // This only happens if isSpecifiedByParameter == true, because the Constant is
  // conditionally declared above  
  connect(constantBlock.y, value_);

   annotation (Icon(coordinateSystem(preserveAspectRatio=false), graphics={
        Rectangle(
          extent={{-80,40},{80,-40}},
          lineColor={28,108,200},
          fillColor={255,255,255},
          fillPattern=FillPattern.Solid),
        Text(
          extent={{-70,30},{70,-32}},
          lineColor={28,108,200},
          textString="Config
Variable"),
        Text(
          extent={{-100,80},{100,50}},
          lineColor={28,108,200},
          fillColor={255,255,255},
          fillPattern=FillPattern.Solid,
          textString=DynamicSelect("", "value = " + String(value, significantDigits=4))),
        Text(
          extent={{-100,-50},{100,-80}},
          lineColor={28,108,200},
          fillColor={255,255,255},
          fillPattern=FillPattern.Solid,
          textString="%name")}),
        Diagram(
        coordinateSystem(preserveAspectRatio=false)));
end ConfigurableReal;

Теперь я хотел бы расширить модель таким образом, чтобы использовать типы количества / единиц, а не только Реалы. Можно ли указать тип переменной через параметр? Например, можно ли объявить переменную, как показано ниже?

parameter String variableType = "Pressure";
parameter typeOf(variableType) variableType;

Если это так, я мог бы определить типы переменных в модели ConfigurableReal для ссылки на объект variableType и написать настраиваемую модель давления следующим образом:

model ConfigurablePressure extends ConfigurableReal(final variableType="Pressure");

Если нет, то есть ли в Modelica что-то вроде параметров типа C #?

В конце концов, я действительно пытаюсь найти способ расширить мою модель ConfigurableReal, чтобы она могла быть ConfigurablePressure, ConfigurableTempera, ConfigurableMassFlowRate, ..., содержащая единицы во входных параметрах и результатах моделирования без необходимости копировать и вставлять код модели. для каждого типа переменной и вручную назначить типы переменных в каждом классе.

Любая помощь приветствуется.

Спасибо, Джастин


person Justin Kauffman    schedule 25.10.2016    source источник


Ответы (1)


Джастин, ты действительно хочешь использовать redeclare + replaceable. Вы упоминаете параметры типа C #. В Modelica есть что-то подобное, но они не совсем выглядят (синтаксически) одинаково, и у них есть некоторые дополнительные ограничения из-за математических ограничений Modelica.

Если вы еще не прочитали главу об архитектуре в моей книге, это даст вам Начните.

Чтобы завершить аналогию с параметрами типа C #, рассмотрим эту модель:

model Circuit
  replaceable Resistor R constrainedby Element;
  ...
end Circuit;

Это говорит о том, что R должен быть подтипом Element. По умолчанию это Resistor, но вы можете это изменить. Обратите внимание, что Element и Resistor или оба типа. Итак, вы меняете тип R, меняя их. Вы меняете с помощью redeclare (см. Книгу).

В этом случае «параметр типа» применяется только к одной переменной R. Но вы можете сделать это более похожим на C # способом:

model Circuit
  replaceable model X = Resistor constrainedby Element;
  X R1;
  X R2;
}

В C # это будет примерно так:

class Circuit<X> where X : Element {
  X R1;
  X R2;
}

(за исключением того, что C # не работает по умолчанию, насколько я помню)

Мне нужно бежать, но я надеюсь, что это поможет.

person Michael Tiller    schedule 25.10.2016