within Modelica.Fluid;
package Sensors
  "Ideal sensor components to extract signals from a fluid connector"
  extends Modelica.Icons.SensorsPackage;

  model Pressure "Ideal pressure sensor"
    extends Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput p(final quantity="Pressure",
                                            final unit="Pa",
                                            displayUnit="bar",
                                            min=0) "Pressure at port"
  equation
    p = port.p;
  end Pressure;

  model Density "Ideal one port density sensor"
    extends Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput d(final quantity="Density",
                                            final unit="kg/m3",
                                            displayUnit="g/cm3",
                                            min=0) "Density in port medium"

  equation
    d = Medium.density(Medium.setState_phX(port.p, inStream(port.h_outflow), inStream(port.Xi_outflow)));
  end Density;

  model DensityTwoPort "Ideal two port density sensor"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput d(final quantity="Density",
                                            final unit="kg/m3",
                                            displayUnit="g/cm3",
                                            min=0)
      "Density of the passing fluid"

  protected
    Medium.Density rho_a_inflow "Density of inflowing fluid at port_a";
    Medium.Density rho_b_inflow
      "Density of inflowing fluid at port_b or rho_a_inflow, if uni-directional flow";
  equation
    if allowFlowReversal then
       rho_a_inflow = Medium.density(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       rho_b_inflow = Medium.density(Medium.setState_phX(port_a.p, port_a.h_outflow, port_a.Xi_outflow));
       d = Modelica.Fluid.Utilities.regStep(port_a.m_flow, rho_a_inflow, rho_b_inflow, m_flow_small);
    else
       d = Medium.density(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       rho_a_inflow = d;
       rho_b_inflow = d;
    end if;
  end DensityTwoPort;

  model Temperature "Ideal one port temperature sensor"
      extends Sensors.BaseClasses.PartialAbsoluteSensor;

    Modelica.Blocks.Interfaces.RealOutput T(final quantity="ThermodynamicTemperature",
                                            final unit = "K", displayUnit = "degC", min=0)
      "Temperature in port medium"

  equation
    T = Medium.temperature(Medium.setState_phX(port.p, inStream(port.h_outflow), inStream(port.Xi_outflow)));
  end Temperature;

  model TemperatureTwoPort "Ideal two port temperature sensor"
    extends Sensors.BaseClasses.PartialFlowSensor;

    Modelica.Blocks.Interfaces.RealOutput T( final quantity="ThermodynamicTemperature",
                                             final unit="K",
                                             min = 0,
                                             displayUnit="degC")
      "Temperature of the passing fluid"

  protected
    Medium.Temperature T_a_inflow "Temperature of inflowing fluid at port_a";
    Medium.Temperature T_b_inflow
      "Temperature of inflowing fluid at port_b or T_a_inflow, if uni-directional flow";
  equation
    if allowFlowReversal then
       T_a_inflow = Medium.temperature(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       T_b_inflow = Medium.temperature(Medium.setState_phX(port_a.p, port_a.h_outflow, port_a.Xi_outflow));
       T = Modelica.Fluid.Utilities.regStep(port_a.m_flow, T_a_inflow, T_b_inflow, m_flow_small);
    else
       T = Medium.temperature(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       T_a_inflow = T;
       T_b_inflow = T;
    end if;
  end TemperatureTwoPort;

  model SpecificEnthalpy "Ideal one port specific enthalpy sensor"
    extends Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput h_out(final quantity="SpecificEnergy",
                                                final unit="J/kg")
      "Specific enthalpy in port medium"

  equation
    h_out = inStream(port.h_outflow);
  end SpecificEnthalpy;

  model SpecificEnthalpyTwoPort
    "Ideal two port sensor for the specific enthalpy"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput h_out(final quantity="SpecificEnergy",
                                                final unit="J/kg")
      "Specific enthalpy of the passing fluid"

  equation
    if allowFlowReversal then
       h_out = Modelica.Fluid.Utilities.regStep(port_a.m_flow, port_b.h_outflow, port_a.h_outflow, m_flow_small);
    else
       h_out = port_b.h_outflow;
    end if;
  end SpecificEnthalpyTwoPort;

  model SpecificEntropy "Ideal one port specific entropy sensor"
    extends Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput s(final quantity="SpecificEntropy",
                                            final unit="J/(kg.K)")
      "Specific entropy in port medium"

  equation
    s = Medium.specificEntropy(Medium.setState_phX(port.p, inStream(port.h_outflow), inStream(port.Xi_outflow)));
  end SpecificEntropy;

  model SpecificEntropyTwoPort "Ideal two port sensor for the specific entropy"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput s(final quantity="SpecificEntropy",
                                            final unit="J/(kg.K)")
      "Specific entropy of the passing fluid"

  protected
    Medium.SpecificEntropy s_a_inflow
      "Specific entropy of inflowing fluid at port_a";
    Medium.SpecificEntropy s_b_inflow
      "Specific entropy of inflowing fluid at port_b or s_a_inflow, if uni-directional flow";
  equation
    if allowFlowReversal then
       s_a_inflow = Medium.specificEntropy(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       s_b_inflow = Medium.specificEntropy(Medium.setState_phX(port_a.p, port_a.h_outflow, port_a.Xi_outflow));
       s = Modelica.Fluid.Utilities.regStep(port_a.m_flow, s_a_inflow, s_b_inflow, m_flow_small);
    else
       s = Medium.specificEntropy(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       s_a_inflow = s;
       s_b_inflow = s;
    end if;
  end SpecificEntropyTwoPort;

  model MassFractions "Ideal one port mass fraction sensor"
    extends Modelica.Fluid.Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    parameter String substanceName = "water" "Name of mass fraction";

    Modelica.Blocks.Interfaces.RealOutput Xi "Mass fraction in port medium"

  protected
    parameter Integer ind(fixed=false)
      "Index of species in vector of independent mass fractions";
    Medium.MassFraction XiVec[Medium.nXi]
      "Mass fraction vector, needed because indexed argument for the operator inStream is not supported";
  initial algorithm
    ind:= -1;
    for i in 1:Medium.nXi loop
      if ( Modelica.Utilities.Strings.isEqual(Medium.substanceNames[i], substanceName)) then
        ind := i;
      end if;
    end for;
    assert(ind > 0, "Mass fraction '" + substanceName + "' is not present in medium '"
           + Medium.mediumName + "'.\n"
           + "Check sensor parameter and medium model.");
  equation
    XiVec = inStream(port.Xi_outflow);
    Xi = XiVec[ind];
  end MassFractions;

  model MassFractionsTwoPort "Ideal two port sensor for mass fraction"
    extends Modelica.Fluid.Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput Xi "Mass fraction in port medium"
    parameter String substanceName = "water" "Name of mass fraction";

  protected
    parameter Integer ind(fixed=false)
      "Index of species in vector of independent mass fractions";
  initial algorithm
    ind:= -1;
    for i in 1:Medium.nXi loop
      if ( Modelica.Utilities.Strings.isEqual(Medium.substanceNames[i], substanceName)) then
        ind := i;
      end if;
    end for;
    assert(ind > 0, "Mass fraction '" + substanceName + "' is not present in medium '"
           + Medium.mediumName + "'.\n"
           + "Check sensor parameter and medium model.");
  equation
    if allowFlowReversal then
       Xi = Modelica.Fluid.Utilities.regStep(port_a.m_flow, port_b.Xi_outflow[ind], port_a.Xi_outflow[ind], m_flow_small);
    else
       Xi = port_b.Xi_outflow[ind];
    end if;
  end MassFractionsTwoPort;

  model TraceSubstances "Ideal one port trace substances sensor"
    extends Sensors.BaseClasses.PartialAbsoluteSensor;
    extends Modelica.Icons.RoundSensor;
    parameter String substanceName = "CO2" "Name of trace substance";

    Modelica.Blocks.Interfaces.RealOutput C "Trace substance in port medium"

  protected
    parameter Integer ind(fixed=false)
      "Index of species in vector of auxiliary substances";
    Medium.ExtraProperty CVec[Medium.nC](
        quantity=Medium.extraPropertiesNames)
      "Trace substances vector, needed because indexed argument for the operator inStream is not supported";
  initial algorithm
    ind:= -1;
    for i in 1:Medium.nC loop
      if ( Modelica.Utilities.Strings.isEqual(Medium.extraPropertiesNames[i], substanceName)) then
        ind := i;
      end if;
    end for;
    assert(ind > 0, "Trace substance '" + substanceName + "' is not present in medium '"
           + Medium.mediumName + "'.\n"
           + "Check sensor parameter and medium model.");
  equation
    CVec = inStream(port.C_outflow);
    C = CVec[ind];
  end TraceSubstances;

  model TraceSubstancesTwoPort "Ideal two port sensor for trace substance"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput C
      "Trace substance of the passing fluid"
    parameter String substanceName = "CO2" "Name of trace substance";

  protected
    parameter Integer ind(fixed=false)
      "Index of species in vector of auxiliary substances";
  initial algorithm
    ind:= -1;
    for i in 1:Medium.nC loop
      if ( Modelica.Utilities.Strings.isEqual(Medium.extraPropertiesNames[i], substanceName)) then
        ind := i;
      end if;
    end for;
    assert(ind > 0, "Trace substance '" + substanceName + "' is not present in medium '"
           + Medium.mediumName + "'.\n"
           + "Check sensor parameter and medium model.");
  equation
    if allowFlowReversal then
       C = Modelica.Fluid.Utilities.regStep(port_a.m_flow, port_b.C_outflow[ind], port_a.C_outflow[ind], m_flow_small);
    else
       C = port_b.C_outflow[ind];
    end if;
  end TraceSubstancesTwoPort;

  model MassFlowRate "Ideal sensor for mass flow rate"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput m_flow(quantity="MassFlowRate",
                                                 final unit="kg/s")
      "Mass flow rate from port_a to port_b"

  equation
    m_flow = port_a.m_flow;
  end MassFlowRate;

  model VolumeFlowRate "Ideal sensor for volume flow rate"
    extends Sensors.BaseClasses.PartialFlowSensor;
    extends Modelica.Icons.RoundSensor;
    Modelica.Blocks.Interfaces.RealOutput V_flow(final quantity="VolumeFlowRate",
                                                 final unit="m3/s")
      "Volume flow rate from port_a to port_b"

  protected
    Medium.Density rho_a_inflow "Density of inflowing fluid at port_a";
    Medium.Density rho_b_inflow
      "Density of inflowing fluid at port_b or rho_a_inflow, if uni-directional flow";
    Medium.Density d "Density of the passing fluid";
  equation
    if allowFlowReversal then
       rho_a_inflow = Medium.density(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       rho_b_inflow = Medium.density(Medium.setState_phX(port_a.p, port_a.h_outflow, port_a.Xi_outflow));
       d = Modelica.Fluid.Utilities.regStep(port_a.m_flow, rho_a_inflow, rho_b_inflow, m_flow_small);
    else
       d = Medium.density(Medium.setState_phX(port_b.p, port_b.h_outflow, port_b.Xi_outflow));
       rho_a_inflow = d;
       rho_b_inflow = d;
    end if;
    V_flow = port_a.m_flow/d;
  end VolumeFlowRate;

  model RelativePressure "Ideal relative pressure sensor"
    extends Sensors.BaseClasses.PartialRelativeSensor;

    Modelica.Blocks.Interfaces.RealOutput p_rel(final quantity="Pressure",
                                                final unit="Pa",
                                                displayUnit="bar")
      "Relative pressure signal"
  equation

    // Relative pressure
    p_rel = port_a.p - port_b.p;
  end RelativePressure;

  model RelativeTemperature "Ideal relative temperature sensor"
    extends Sensors.BaseClasses.PartialRelativeSensor;

    Modelica.Blocks.Interfaces.RealOutput T_rel(final quantity="ThermodynamicTemperature",
                                                final unit = "K", displayUnit = "degC", min=0)
      "Relative temperature signal"
  equation
    // Relative temperature
    T_rel = Medium.temperature(Medium.setState_phX(port_a.p, inStream(port_a.h_outflow), inStream(port_a.Xi_outflow))) -
            Medium.temperature(Medium.setState_phX(port_b.p, inStream(port_b.h_outflow), inStream(port_b.Xi_outflow)));
  end RelativeTemperature;

  package BaseClasses
    "Base classes used in the Sensors package (only of interest to build new component models)"
    extends Modelica.Icons.BasesPackage;

    partial model PartialAbsoluteSensor
      "Partial component to model a sensor that measures a potential variable"

      replaceable package Medium=Modelica.Media.Interfaces.PartialMedium
        "Medium in the sensor"

      Modelica.Fluid.Interfaces.FluidPort_a port(redeclare package Medium=Medium, m_flow(min=0))

    equation
      port.m_flow = 0;
      port.h_outflow = Medium.h_default;
      port.Xi_outflow = Medium.X_default[1:Medium.nXi];
      port.C_outflow = zeros(Medium.nC);
    end PartialAbsoluteSensor;

    model PartialRelativeSensor
      "Partial component to model a sensor that measures the difference between two potential variables"
      extends Modelica.Icons.RectangularSensor;
      replaceable package Medium =
        Modelica.Media.Interfaces.PartialMedium "Medium in the sensor"

      Modelica.Fluid.Interfaces.FluidPort_a port_a(m_flow(min=0),
                                    redeclare package Medium = Medium)
      Modelica.Fluid.Interfaces.FluidPort_b port_b(m_flow(min=0),
                                    redeclare package Medium = Medium)

    equation
      // Zero flow equations for connectors
      port_a.m_flow = 0;
      port_b.m_flow = 0;

      // No contribution of specific quantities
      port_a.h_outflow = Medium.h_default;
      port_b.h_outflow = Medium.h_default;
      port_a.Xi_outflow = Medium.X_default[1:Medium.nXi];
      port_b.Xi_outflow = Medium.X_default[1:Medium.nXi];
      port_a.C_outflow  = zeros(Medium.nC);
      port_b.C_outflow  = zeros(Medium.nC);
    end PartialRelativeSensor;

    partial model PartialFlowSensor
      "Partial component to model sensors that measure flow properties"
      extends Modelica.Fluid.Interfaces.PartialTwoPort;

      parameter Medium.MassFlowRate m_flow_nominal = system.m_flow_nominal
        "Nominal value of m_flow = port_a.m_flow"
      parameter Medium.MassFlowRate m_flow_small(min=0) = if system.use_eps_Re then system.eps_m_flow*m_flow_nominal else system.m_flow_small
        "Regularization for bi-directional flow in the region |m_flow| < m_flow_small (m_flow_small > 0 required)"

    equation
      // mass balance
      0 = port_a.m_flow + port_b.m_flow;

      // momentum equation (no pressure loss)
      port_a.p = port_b.p;

      // isenthalpic state transformation (no storage and no loss of energy)
      port_a.h_outflow = inStream(port_b.h_outflow);
      port_b.h_outflow = inStream(port_a.h_outflow);

      port_a.Xi_outflow = inStream(port_b.Xi_outflow);
      port_b.Xi_outflow = inStream(port_a.Xi_outflow);

      port_a.C_outflow = inStream(port_b.C_outflow);
      port_b.C_outflow = inStream(port_a.C_outflow);
    end PartialFlowSensor;

  end BaseClasses;
end Sensors;


within Modelica.Fluid;
package Sources "Define fixed or prescribed boundary conditions"
  extends Modelica.Icons.SourcesPackage;
  model FixedBoundary "Boundary source component"
    import Modelica.Media.Interfaces.Choices.IndependentVariables;
    extends Sources.BaseClasses.PartialSource;
    parameter Boolean use_p=true "Select p or d"
    parameter Medium.AbsolutePressure p=Medium.p_default "Boundary pressure"
  parameter Medium.Density d=
   (if use_T then Medium.density_pTX(
                    Medium.p_default,Medium.T_default,Medium.X_default)
    else Medium.density_phX(
                    Medium.p_default,Medium.h_default,Medium.X_default))
      "Boundary density"
    parameter Boolean use_T=true "Select T or h"
    parameter Medium.Temperature T = Medium.T_default "Boundary temperature"
    parameter Medium.SpecificEnthalpy h = Medium.h_default
      "Boundary specific enthalpy"
    parameter Medium.MassFraction X[Medium.nX] = Medium.X_default
      "Boundary mass fractions m_i/m"
    parameter Medium.ExtraProperty C[Medium.nC](
         quantity=Medium.extraPropertiesNames) = Medium.C_default
      "Boundary trace substances"
  protected
    Medium.ThermodynamicState state;
  equation
    Modelica.Fluid.Utilities.checkBoundary(Medium.mediumName, Medium.substanceNames,
                                          Medium.singleState, use_p, X,
                                          "FixedBoundary");
    if use_p or Medium.singleState then
       // p given
       if use_T then
          // p,T,X given
          state = Medium.setState_pTX(p, T, X);
       else
          // p,h,X given
          state = Medium.setState_phX(p, h, X);
       end if;

       if Medium.ThermoStates == IndependentVariables.dTX then
          medium.d = Medium.density(state);
       else
          medium.p = Medium.pressure(state);
       end if;

       if Medium.ThermoStates == IndependentVariables.ph or
          Medium.ThermoStates == IndependentVariables.phX then
          medium.h = Medium.specificEnthalpy(state);
       else
          medium.T = Medium.temperature(state);
       end if;

    else
       // d given
       if use_T then
          // d,T,X given
          state = Medium.setState_dTX(d, T, X);

          if Medium.ThermoStates == IndependentVariables.dTX then
             medium.d = Medium.density(state);
          else
             medium.p = Medium.pressure(state);
          end if;

          if Medium.ThermoStates == IndependentVariables.ph or
             Medium.ThermoStates == IndependentVariables.phX then
             medium.h = Medium.specificEnthalpy(state);
          else
             medium.T = Medium.temperature(state);
          end if;

       else
          // d,h,X given
          medium.d = d;
          medium.h = h;
          state = Medium.setState_dTX(d,T,X);
       end if;
    end if;

    medium.Xi = X[1:Medium.nXi];

    ports.C_outflow = fill(C, nPorts);
  end FixedBoundary;

  model Boundary_pT
    "Boundary with prescribed pressure, temperature, composition and trace substances"
    import Modelica.Media.Interfaces.Choices.IndependentVariables;

    extends Sources.BaseClasses.PartialSource;
    parameter Boolean use_p_in = false
      "Get the pressure from the input connector"
    parameter Boolean use_T_in= false
      "Get the temperature from the input connector"
    parameter Boolean use_X_in = false
      "Get the composition from the input connector"
    parameter Boolean use_C_in = false
      "Get the trace substances from the input connector"
    parameter Medium.AbsolutePressure p = Medium.p_default
      "Fixed value of pressure"
    parameter Medium.Temperature T = Medium.T_default
      "Fixed value of temperature"
    parameter Medium.MassFraction X[Medium.nX] = Medium.X_default
      "Fixed value of composition"
    parameter Medium.ExtraProperty C[Medium.nC](
         quantity=Medium.extraPropertiesNames) = Medium.C_default
      "Fixed values of trace substances"
    Modelica.Blocks.Interfaces.RealInput p_in(unit="Pa") if use_p_in
      "Prescribed boundary pressure"
    Modelica.Blocks.Interfaces.RealInput T_in(unit="K") if use_T_in
      "Prescribed boundary temperature"
    Modelica.Blocks.Interfaces.RealInput X_in[Medium.nX](each unit="1") if use_X_in
      "Prescribed boundary composition"
    Modelica.Blocks.Interfaces.RealInput C_in[Medium.nC] if use_C_in
      "Prescribed boundary trace substances"
  protected
    Modelica.Blocks.Interfaces.RealInput p_in_internal(unit="Pa")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput T_in_internal(unit="K")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput X_in_internal[Medium.nX](each unit="1")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput C_in_internal[Medium.nC]
      "Needed to connect to conditional connector";
  equation
    Modelica.Fluid.Utilities.checkBoundary(Medium.mediumName, Medium.substanceNames,
      Medium.singleState, true, X_in_internal, "Boundary_pT");
    connect(p_in, p_in_internal);
    connect(T_in, T_in_internal);
    connect(X_in, X_in_internal);
    connect(C_in, C_in_internal);
    if not use_p_in then
      p_in_internal = p;
    end if;
    if not use_T_in then
      T_in_internal = T;
    end if;
    if not use_X_in then
      X_in_internal = X;
    end if;
    if not use_C_in then
      C_in_internal = C;
    end if;
    medium.p = p_in_internal;
    if Medium.ThermoStates == IndependentVariables.ph or
       Medium.ThermoStates == IndependentVariables.phX then
       medium.h = Medium.specificEnthalpy(Medium.setState_pTX(p_in_internal, T_in_internal, X_in_internal));
    else
       medium.T = T_in_internal;
    end if;
    medium.Xi = X_in_internal[1:Medium.nXi];
    ports.C_outflow = fill(C_in_internal, nPorts);
  end Boundary_pT;

  model Boundary_ph
    "Boundary with prescribed pressure, specific enthalpy, composition and trace substances"
    import Modelica.Media.Interfaces.Choices.IndependentVariables;
    extends Sources.BaseClasses.PartialSource;
    parameter Boolean use_p_in = false
      "Get the pressure from the input connector"
    parameter Boolean use_h_in= false
      "Get the specific enthalpy from the input connector"
    parameter Boolean use_X_in = false
      "Get the composition from the input connector"
    parameter Boolean use_C_in = false
      "Get the trace substances from the input connector"
    parameter Medium.AbsolutePressure p = Medium.p_default
      "Fixed value of pressure"
    parameter Medium.SpecificEnthalpy h = Medium.h_default
      "Fixed value of specific enthalpy"
    parameter Medium.MassFraction X[Medium.nX] = Medium.X_default
      "Fixed value of composition"
    parameter Medium.ExtraProperty C[Medium.nC](
         quantity=Medium.extraPropertiesNames) = Medium.C_default
      "Fixed values of trace substances"
    Modelica.Blocks.Interfaces.RealInput p_in(unit="Pa") if use_p_in
      "Prescribed boundary pressure"
    Modelica.Blocks.Interfaces.RealInput h_in(unit="J/kg") if use_h_in
      "Prescribed boundary specific enthalpy"
    Modelica.Blocks.Interfaces.RealInput X_in[Medium.nX](each unit="1") if use_X_in
      "Prescribed boundary composition"
    Modelica.Blocks.Interfaces.RealInput C_in[Medium.nC] if use_C_in
      "Prescribed boundary trace substances"
  protected
    Modelica.Blocks.Interfaces.RealInput p_in_internal(unit="Pa")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput h_in_internal(unit="J/kg")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput X_in_internal[Medium.nX](each unit="1")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput C_in_internal[Medium.nC]
      "Needed to connect to conditional connector";
  equation
    Modelica.Fluid.Utilities.checkBoundary(Medium.mediumName, Medium.substanceNames,
      Medium.singleState, true, X_in_internal, "Boundary_ph");
    connect(p_in, p_in_internal);
    connect(h_in, h_in_internal);
    connect(X_in, X_in_internal);
    connect(C_in, C_in_internal);
    if not use_p_in then
      p_in_internal = p;
    end if;
    if not use_h_in then
      h_in_internal = h;
    end if;
    if not use_X_in then
      X_in_internal = X;
    end if;
    if not use_C_in then
      C_in_internal = C;
    end if;
    medium.p = p_in_internal;
    if Medium.ThermoStates == IndependentVariables.ph or
       Medium.ThermoStates == IndependentVariables.phX then
       medium.h = h_in_internal;
    else
       medium.T = Medium.temperature(Medium.setState_phX(p_in_internal, h_in_internal, X_in_internal));
    end if;
    medium.Xi = X_in_internal[1:Medium.nXi];
    ports.C_outflow = fill(C_in_internal, nPorts);
  end Boundary_ph;

  model MassFlowSource_T
    "Ideal flow source that produces a prescribed mass flow with prescribed temperature, mass fraction and trace substances"
    import Modelica.Media.Interfaces.Choices.IndependentVariables;
    extends Sources.BaseClasses.PartialFlowSource(nPorts(min=1));
    parameter Boolean use_m_flow_in = false
      "Get the mass flow rate from the input connector"
    parameter Boolean use_T_in= false
      "Get the temperature from the input connector"
    parameter Boolean use_X_in = false
      "Get the composition from the input connector"
    parameter Boolean use_C_in = false
      "Get the trace substances from the input connector"
    parameter Medium.MassFlowRate m_flow = 0
      "Fixed mass flow rate going out of the fluid port"
    parameter Medium.Temperature T = Medium.T_default
      "Fixed value of temperature"
    parameter Medium.MassFraction X[Medium.nX] = Medium.X_default
      "Fixed value of composition"
    parameter Medium.ExtraProperty C[Medium.nC](
         quantity=Medium.extraPropertiesNames) = Medium.C_default
      "Fixed values of trace substances"
    Modelica.Blocks.Interfaces.RealInput m_flow_in(unit="kg/s") if use_m_flow_in
      "Prescribed mass flow rate"
    Modelica.Blocks.Interfaces.RealInput T_in(unit="K") if use_T_in
      "Prescribed fluid temperature"
    Modelica.Blocks.Interfaces.RealInput X_in[Medium.nX](each unit="1") if use_X_in
      "Prescribed fluid composition"
    Modelica.Blocks.Interfaces.RealInput C_in[Medium.nC] if use_C_in
      "Prescribed boundary trace substances"
  protected
    Modelica.Blocks.Interfaces.RealInput m_flow_in_internal(unit="kg/s")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput T_in_internal(unit="K")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput X_in_internal[Medium.nX](each unit="1")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput C_in_internal[Medium.nC]
      "Needed to connect to conditional connector";
  equation
    Utilities.checkBoundary(Medium.mediumName, Medium.substanceNames,
      Medium.singleState, true, X_in_internal, "MassFlowSource_T");
    connect(m_flow_in, m_flow_in_internal);
    connect(T_in, T_in_internal);
    connect(X_in, X_in_internal);
    connect(C_in, C_in_internal);
    if not use_m_flow_in then
      m_flow_in_internal = m_flow;
    end if;
    if not use_T_in then
      T_in_internal = T;
    end if;
    if not use_X_in then
      X_in_internal = X;
    end if;
    if not use_C_in then
      C_in_internal = C;
    end if;
    if Medium.ThermoStates == IndependentVariables.ph or
       Medium.ThermoStates == IndependentVariables.phX then
       medium.h = Medium.specificEnthalpy(Medium.setState_pTX(medium.p, T_in_internal, X_in_internal));
    else
       medium.T = T_in_internal;
    end if;
    sum(ports.m_flow) = -m_flow_in_internal;
    medium.Xi = X_in_internal[1:Medium.nXi];
    ports.C_outflow = fill(C_in_internal, nPorts);
  end MassFlowSource_T;

  model MassFlowSource_h
    "Ideal flow source that produces a prescribed mass flow with prescribed specific enthalpy, mass fraction and trace substances"
    import Modelica.Media.Interfaces.Choices.IndependentVariables;
    extends Sources.BaseClasses.PartialFlowSource(nPorts(min=1));
    parameter Boolean use_m_flow_in = false
      "Get the mass flow rate from the input connector"
    parameter Boolean use_h_in= false
      "Get the specific enthalpy from the input connector"
    parameter Boolean use_X_in = false
      "Get the composition from the input connector"
    parameter Boolean use_C_in = false
      "Get the trace substances from the input connector"
    parameter Medium.MassFlowRate m_flow = 0
      "Fixed mass flow rate going out of the fluid port"
    parameter Medium.SpecificEnthalpy h = Medium.h_default
      "Fixed value of specific enthalpy"
    parameter Medium.MassFraction X[Medium.nX] = Medium.X_default
      "Fixed value of composition"
    parameter Medium.ExtraProperty C[Medium.nC](
         quantity=Medium.extraPropertiesNames) = Medium.C_default
      "Fixed values of trace substances"
    Modelica.Blocks.Interfaces.RealInput m_flow_in(unit="kg/s") if use_m_flow_in
      "Prescribed mass flow rate"
    Modelica.Blocks.Interfaces.RealInput h_in(unit="J/kg") if use_h_in
      "Prescribed fluid specific enthalpy"
    Modelica.Blocks.Interfaces.RealInput X_in[Medium.nX](each unit="1") if use_X_in
      "Prescribed fluid composition"
    Modelica.Blocks.Interfaces.RealInput C_in[Medium.nC] if use_C_in
      "Prescribed boundary trace substances"
  protected
    Modelica.Blocks.Interfaces.RealInput m_flow_in_internal(unit="kg/s")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput h_in_internal(unit="J/kg")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput X_in_internal[Medium.nX](each unit="1")
      "Needed to connect to conditional connector";
    Modelica.Blocks.Interfaces.RealInput C_in_internal[Medium.nC]
      "Needed to connect to conditional connector";
  equation
    Utilities.checkBoundary(Medium.mediumName, Medium.substanceNames,
      Medium.singleState, true, X_in_internal, "MassFlowSource_h");
    connect(m_flow_in, m_flow_in_internal);
    connect(h_in, h_in_internal);
    connect(X_in, X_in_internal);
    connect(C_in, C_in_internal);
    if not use_m_flow_in then
      m_flow_in_internal = m_flow;
    end if;
    if not use_h_in then
      h_in_internal = h;
    end if;
    if not use_X_in then
      X_in_internal = X;
    end if;
    if not use_C_in then
      C_in_internal = C;
    end if;
    if Medium.ThermoStates == IndependentVariables.ph or
       Medium.ThermoStates == IndependentVariables.phX then
       medium.h = h_in_internal;
    else
       medium.T = Medium.temperature(Medium.setState_phX(medium.p, h_in_internal, X_in_internal));
    end if;
    sum(ports.m_flow) = -m_flow_in_internal;
    medium.Xi = X_in_internal[1:Medium.nXi];
    ports.C_outflow = fill(C_in_internal, nPorts);
  end MassFlowSource_h;

  package BaseClasses
    "Base classes used in the Sources package (only of interest to build new component models)"
    extends Modelica.Icons.BasesPackage;
  partial model PartialSource
      "Partial component source with one fluid connector"
      import Modelica.Constants;

    parameter Integer nPorts=0 "Number of ports"

    replaceable package Medium =
        Modelica.Media.Interfaces.PartialMedium
        "Medium model within the source"

    Medium.BaseProperties medium "Medium in the source";

    Interfaces.FluidPorts_b ports[nPorts](
                       redeclare each package Medium = Medium,
                       m_flow(each max=if flowDirection==Types.PortFlowDirection.Leaving then 0 else
                                       +Constants.inf,
                              each min=if flowDirection==Types.PortFlowDirection.Entering then 0 else
                                       -Constants.inf))
    protected
    parameter Types.PortFlowDirection flowDirection=
                     Types.PortFlowDirection.Bidirectional
        "Allowed flow direction"
  equation
    // Only one connection allowed to a port to avoid unwanted ideal mixing
    for i in 1:nPorts loop
      assert(cardinality(ports[i]) <= 1,"
each ports[i] of boundary shall at most be connected to one component.
If two or more connections are present, ideal mixing takes
place with these connections, which is usually not the intention
of the modeller. Increase nPorts to add an additional port.
");

       ports[i].p          = medium.p;
       ports[i].h_outflow  = medium.h;
       ports[i].Xi_outflow = medium.Xi;
    end for;
  end PartialSource;

  partial model PartialFlowSource
      "Partial component source with one fluid connector"
    import Modelica.Constants;

    parameter Integer nPorts=0 "Number of ports"

    replaceable package Medium =
        Modelica.Media.Interfaces.PartialMedium
        "Medium model within the source"

    Medium.BaseProperties medium "Medium in the source";

    Interfaces.FluidPort_b ports[nPorts](
                       redeclare each package Medium = Medium,
                       m_flow(each max=if flowDirection==Types.PortFlowDirection.Leaving then 0 else
                                       +Constants.inf,
                              each min=if flowDirection==Types.PortFlowDirection.Entering then 0 else
                                       -Constants.inf))
    protected
    parameter Types.PortFlowDirection flowDirection=
                     Types.PortFlowDirection.Bidirectional
        "Allowed flow direction"
  equation
    assert(abs(sum(abs(ports.m_flow)) - max(abs(ports.m_flow))) <= Modelica.Constants.small, "FlowSource only supports one connection with flow");
    assert(nPorts > 0, "At least one port needs to be present (nPorts > 0), otherwise the model is singular");
    // Only one connection allowed to a port to avoid unwanted ideal mixing
    for i in 1:nPorts loop
      assert(cardinality(ports[i]) <= 1,"
each ports[i] of boundary shall at most be connected to one component.
If two or more connections are present, ideal mixing takes
place with these connections, which is usually not the intention
of the modeller. Increase nPorts to add an additional port.
");
       ports[i].p          = medium.p;
       ports[i].h_outflow  = medium.h;
       ports[i].Xi_outflow = medium.Xi;
    end for;
  end PartialFlowSource;
  end BaseClasses;
end Sources;


within Modelica.Fluid;
model System
  "System properties and default values (ambient, flow direction, initialization)"

  package Medium = Modelica.Media.Interfaces.PartialMedium
    "Medium model for default start values"
  parameter SI.AbsolutePressure p_ambient=101325
    "Default ambient pressure"
  parameter SI.Temperature T_ambient=293.15
    "Default ambient temperature"
  parameter SI.Acceleration g=Modelica.Constants.g_n
    "Constant gravity acceleration"

  // Assumptions
  parameter Boolean allowFlowReversal = true
    "= false to restrict to design flow direction (port_a -> port_b)"
  parameter Modelica.Fluid.Types.Dynamics energyDynamics=
    Modelica.Fluid.Types.Dynamics.DynamicFreeInitial
    "Default formulation of energy balances"
  parameter Modelica.Fluid.Types.Dynamics massDynamics=
    energyDynamics "Default formulation of mass balances"
  final parameter Modelica.Fluid.Types.Dynamics substanceDynamics=
    massDynamics "Default formulation of substance balances"
  final parameter Modelica.Fluid.Types.Dynamics traceDynamics=
    massDynamics "Default formulation of trace substance balances"
  parameter Modelica.Fluid.Types.Dynamics momentumDynamics=
    Modelica.Fluid.Types.Dynamics.SteadyState
    "Default formulation of momentum balances, if options available"

  // Initialization
  parameter SI.MassFlowRate m_flow_start = 0
    "Default start value for mass flow rates"
  parameter SI.AbsolutePressure p_start = p_ambient
    "Default start value for pressures"
  parameter SI.Temperature T_start = T_ambient
    "Default start value for temperatures"
  // Advanced
  parameter Boolean use_eps_Re = false
    "= true to determine turbulent region automatically using Reynolds number"
  parameter SI.MassFlowRate m_flow_nominal = if use_eps_Re then 1 else 1e2*m_flow_small
    "Default nominal mass flow rate"
  parameter Real eps_m_flow(min=0) = 1e-4
    "Regularization of zero flow for |m_flow| < eps_m_flow*m_flow_nominal"
  parameter SI.AbsolutePressure dp_small(min=0) = 1
    "Default small pressure drop for regularization of laminar and zero flow"
  parameter SI.MassFlowRate m_flow_small(min=0) = 1e-2
    "Default small mass flow rate for regularization of laminar and zero flow"
initial equation
  //assert(use_eps_Re, "*** Using classic system.m_flow_small and system.dp_small."
  //       + " They do not distinguish between laminar flow and regularization of zero flow."
  //       + " Absolute small values are error prone for models with local nominal values."
  //       + " Moreover dp_small can generally be obtained automatically."
  //       + " Please update the model to new system.use_eps_Re = true  (see system, Advanced tab). ***",
  //       level=AssertionLevel.warning);
end System;


Common types for fluid models

within Modelica.Fluid;
package Types "Common types for fluid models"
  extends Modelica.Icons.TypesPackage;

  type HydraulicConductance = Modelica.Icons.TypeReal (
      final quantity="HydraulicConductance",
      final unit="kg/(s.Pa)") "Real type for hydraulic conductance";
  type HydraulicResistance = Modelica.Icons.TypeReal (
      final quantity="HydraulicResistance",
      final unit="Pa.s/kg") "Real type for hydraulic resistance";

  type Roughness = Modelica.Icons.TypeReal (final quantity="Length", final unit="m", displayUnit="mm", min=0)
    "Real type for roughness of a pipe"
  type Dynamics = enumeration(
      DynamicFreeInitial
        "DynamicFreeInitial -- Dynamic balance, Initial guess value",
      FixedInitial "FixedInitial -- Dynamic balance, Initial value fixed",
      SteadyStateInitial
        "SteadyStateInitial -- Dynamic balance, Steady state initial with guess value",

      SteadyState "SteadyState -- Steady state balance, Initial guess value")
    "Enumeration to define definition of balance equations"

  type CvTypes = enumeration(
      Av "Av (metric) flow coefficient",
      Kv "Kv (metric) flow coefficient",
      Cv "Cv (US) flow coefficient",
      OpPoint "Av defined by operating point")
    "Enumeration to define the choice of valve flow coefficient"

  type PortFlowDirection = enumeration(
      Entering "Fluid flow is only entering",
      Leaving "Fluid flow is only leaving",
      Bidirectional "No restrictions on fluid flow (flow reversal possible)")
    "Enumeration to define whether flow reversal is allowed"

  type ModelStructure = enumeration(
      av_vb "av_vb: port_a - volume - flow model - volume - port_b",
      a_v_b "a_v_b: port_a - flow model - volume - flow model - port_b",
      av_b "av_b: port_a - volume - flow model - port_b",
      a_vb "a_vb: port_a - flow model - volume - port_b")
    "Enumeration with choices for model structure in distributed pipe model"
  type CheckValveHomotopyType = enumeration(Open, Closed, NoHomotopy)
   "Enumeration with choices for check valve homotopy"
end Types;


within Modelica.Fluid;
package Utilities
  "Utility models to construct fluid components (should not be used directly)"
  extends Modelica.Icons.UtilitiesPackage;

  function checkBoundary "Check whether boundary definition is correct"
    extends Modelica.Icons.Function;
    input String mediumName;
    input String substanceNames[:] "Names of substances";
    input Boolean singleState;
    input Boolean define_p;
    input Real X_boundary[:];
    input String modelName = "??? boundary ???";
  protected
    Integer nX = size(X_boundary,1);
    String X_str;
  algorithm
    assert(not singleState or singleState and define_p, "
Wrong value of parameter define_p (= false) in model \"" + modelName + "\":
The selected medium \"" + mediumName + "\" has Medium.singleState=true.
Therefore, an boundary density cannot be defined and
define_p = true is required.
");

    for i in 1:nX loop
      assert(X_boundary[i] >= 0.0, "
Wrong boundary mass fractions in medium \""
  + mediumName + "\" in model \"" + modelName + "\":
The boundary value X_boundary("
                              + String(i) + ") = " + String(
        X_boundary[i]) + "
is negative. It must be positive.
");
    end for;

    if nX > 0 and abs(sum(X_boundary) - 1.0) > 1e-10 then
       X_str :="";
       for i in 1:nX loop
          X_str :=X_str + "   X_boundary[" + String(i) + "] = " + String(X_boundary[
          i]) + " \"" + substanceNames[i] + "\"\n";
       end for;
       Modelica.Utilities.Streams.error(
          "The boundary mass fractions in medium \"" + mediumName + "\" in model \"" + modelName + "\"\n" +
          "do not sum up to 1. Instead, sum(X_boundary) = " + String(sum(X_boundary)) + ":\n"
          + X_str);
    end if;
  end checkBoundary;

  function regRoot
    "Anti-symmetric square root approximation with finite derivative in the origin"
    extends Modelica.Icons.Function;
    input Real x;
    input Real delta=0.01
      "Range of significant deviation from sqrt(abs(x))*sgn(x)";
    output Real y;
  algorithm
    y := x/(x*x+delta*delta)^0.25;
  end regRoot;

  function regRoot_der "Derivative of regRoot"
    extends Modelica.Icons.Function;
    input Real x;
    input Real delta=0.01 "Range of significant deviation from sqrt(x)";
    input Real dx "Derivative of x";
    output Real dy;
  algorithm
    dy := dx*0.5*(x*x+2*delta*delta)/((x*x+delta*delta)^1.25);
  end regRoot_der;

  function regSquare
    "Anti-symmetric square approximation with non-zero derivative in the origin"
    extends Modelica.Icons.Function;
    input Real x;
    input Real delta=0.01 "Range of significant deviation from x^2*sgn(x)";
    output Real y;
  algorithm
    y := x*sqrt(x*x+delta*delta);
  end regSquare;

  function regPow
    "Anti-symmetric power approximation with non-zero derivative in the origin"
    extends Modelica.Icons.Function;
    input Real x;
    input Real a;
    input Real delta=0.01 "Range of significant deviation from x^a*sgn(x)";
    output Real y;
  algorithm
    y := x*(x*x+delta*delta)^((a-1)/2);
  end regPow;

  function regRoot2
    "Anti-symmetric approximation of square root with discontinuous factor so that the first derivative is finite and continuous"

    extends Modelica.Icons.Function;
    input Real x "Abscissa value";
    input Real x_small(min=0)=0.01 "Approximation of function for |x| <= x_small";
    input Real k1(min=0)=1 "y = if x>=0 then sqrt(k1*x) else -sqrt(k2*|x|)";
    input Real k2(min=0)=1 "y = if x>=0 then sqrt(k1*x) else -sqrt(k2*|x|)";
    input Boolean use_yd0 = false "= true, if yd0 shall be used";
    input Real yd0(min=0)=1 "Desired derivative at x=0: dy/dx = yd0";
    output Real y "Ordinate value";
  protected
    Real sqrt_k1 = if k1 > 0 then sqrt(k1) else 0;
    Real sqrt_k2 = if k2 > 0 then sqrt(k2) else 0;
    encapsulated function regRoot2_utility
      "Interpolating with two 3-order polynomials with a prescribed derivative at x=0"
      import Modelica;
      extends Modelica.Icons.Function;
      import Modelica.Fluid.Utilities.evaluatePoly3_derivativeAtZero;
      input Real x;
      input Real x1 "Approximation of function abs(x) < x1";
      input Real k1 "y = if x>=0 then sqrt(k1*x) else -sqrt(k2*|x|); k1 >= k2";
      input Real k2 "y = if x>=0 then sqrt(k1*x) else -sqrt(k2*|x|))";
      input Boolean use_yd0 "= true, if yd0 shall be used";
      input Real yd0(min=0) "Desired derivative at x=0: dy/dx = yd0";
      output Real y;
    protected
       Real x2;
       Real xsqrt1;
       Real xsqrt2;
       Real y1;
       Real y2;
       Real y1d;
       Real y2d;
       Real w;
       Real y0d;
       Real w1;
       Real w2;
       Real sqrt_k1 = if k1 > 0 then sqrt(k1) else 0;
       Real sqrt_k2 = if k2 > 0 then sqrt(k2) else 0;
    algorithm
       if k2 > 0 then
          // Since k1 >= k2 required, k2 > 0 means that k1 > 0
          x2 :=-x1*(k2/k1);
       elseif k1 > 0 then
          x2 := -x1;
       else
          y := 0;
          return;
       end if;

       if x <= x2 then
          y := -sqrt_k2*sqrt(abs(x));
       else
          y1 :=sqrt_k1*sqrt(x1);
          y2 :=-sqrt_k2*sqrt(abs(x2));
          y1d :=sqrt_k1/sqrt(x1)/2;
          y2d :=sqrt_k2/sqrt(abs(x2))/2;

          if use_yd0 then
             y0d :=yd0;
          else
             /* Determine derivative, such that first and second derivative
              of left and right polynomial are identical at x=0:
           _
           Basic equations:
              y_right = a1*(x/x1) + a2*(x/x1)^2 + a3*(x/x1)^3
              y_left  = b1*(x/x2) + b2*(x/x2)^2 + b3*(x/x2)^3
              yd_right*x1 = a1 + 2*a2*(x/x1) + 3*a3*(x/x1)^2
              yd_left *x2 = b1 + 2*b2*(x/x2) + 3*b3*(x/x2)^2
              ydd_right*x1^2 = 2*a2 + 6*a3*(x/x1)
              ydd_left *x2^2 = 2*b2 + 6*b3*(x/x2)
           _
           Conditions (6 equations for 6 unknowns):
                     y1 = a1 + a2 + a3
                     y2 = b1 + b2 + b3
                 y1d*x1 = a1 + 2*a2 + 3*a3
                 y2d*x2 = b1 + 2*b2 + 3*b3
                    y0d = a1/x1 = b1/x2
                   y0dd = 2*a2/x1^2 = 2*b2/x2^2
           _
           Derived equations:
              b1 = a1*x2/x1
              b2 = a2*(x2/x1)^2
              b3 = y2 - b1 - b2
                 = y2 - a1*(x2/x1) - a2*(x2/x1)^2
              a3 = y1 - a1 - a2
           _
           Remaining equations
              y1d*x1 = a1 + 2*a2 + 3*(y1 - a1 - a2)
                     = 3*y1 - 2*a1 - a2
              y2d*x2 = a1*(x2/x1) + 2*a2*(x2/x1)^2 +
                       3*(y2 - a1*(x2/x1) - a2*(x2/x1)^2)
                     = 3*y2 - 2*a1*(x2/x1) - a2*(x2/x1)^2
              y0d    = a1/x1
           _
           Solving these equations results in y0d below
           (note, the denominator "(1-w)" is always non-zero, because w is negative)
           */
             w :=x2/x1;
             y0d := ( (3*y2 - x2*y2d)/w - (3*y1 - x1*y1d)*w) /(2*x1*(1 - w));
          end if;

          /* Modify derivative y0d, such that the polynomial is
           monotonically increasing. A sufficient condition is
             0 <= y0d <= sqrt(8.75*k_i/|x_i|)
        */
          w1 :=sqrt_k1*sqrt(8.75/x1);
          w2 :=sqrt_k2*sqrt(8.75/abs(x2));
          y0d :=smooth(2, min(y0d, 0.9*min(w1, w2)));

          /* Perform interpolation in scaled polynomial:
           y_new = y/y1
           x_new = x/x1
        */
          y := y1*(if x >= 0 then evaluatePoly3_derivativeAtZero(x/x1,1,1,y1d*x1/y1,y0d*x1/y1) else
                                  evaluatePoly3_derivativeAtZero(x/x1,x2/x1,y2/y1,y2d*x1/y1,y0d*x1/y1));
       end if;
    end regRoot2_utility;
  algorithm
    y := smooth(2, if x >= x_small then sqrt_k1*sqrt(x) else
                   if x <= -x_small then -sqrt_k2*sqrt(abs(x)) else
                   if k1 >= k2 then regRoot2_utility(x,x_small,k1,k2,use_yd0,yd0) else
                                   -regRoot2_utility(-x,x_small,k2,k1,use_yd0,yd0));
  end regRoot2;

  function regSquare2
    "Anti-symmetric approximation of square with discontinuous factor so that the first derivative is non-zero and is continuous"
    extends Modelica.Icons.Function;
    input Real x "Abscissa value";
    input Real x_small(min=0)=0.01
      "Approximation of function for |x| <= x_small";
    input Real k1(min=0)=1 "y = (if x>=0 then k1 else k2)*x*|x|";
    input Real k2(min=0)=1 "y = (if x>=0 then k1 else k2)*x*|x|";
    input Boolean use_yd0 = false "= true, if yd0 shall be used";
    input Real yd0(min=0)=1 "Desired derivative at x=0: dy/dx = yd0";
    output Real y "Ordinate value";
  protected
    encapsulated function regSquare2_utility
      "Interpolating with two 3-order polynomials with a prescribed derivative at x=0"
      import Modelica;
      extends Modelica.Icons.Function;
      import Modelica.Fluid.Utilities.evaluatePoly3_derivativeAtZero;
       input Real x;
       input Real x1 "Approximation of function abs(x) < x1";
       input Real k1 "y = (if x>=0 then k1 else -k2)*x*|x|; k1 >= k2";
       input Real k2 "y = (if x>=0 then k1 else -k2)*x*|x|";
       input Boolean use_yd0 = false "= true, if yd0 shall be used";
       input Real yd0(min=0)=1 "Desired derivative at x=0: dy/dx = yd0";
       output Real y;
    protected
       Real x2;
       Real y1;
       Real y2;
       Real y1d;
       Real y2d;
       Real w;
       Real w1;
       Real w2;
       Real y0d;
       Real ww;
    algorithm
       // x2 :=-x1*(k2/k1)^2;
       x2 := -x1;
       if x <= x2 then
          y := -k2*x^2;
       else
           y1 := k1*x1^2;
           y2 :=-k2*x2^2;
          y1d := k1*2*x1;
          y2d :=-k2*2*x2;
          if use_yd0 then
             y0d :=yd0;
          else
             /* Determine derivative, such that first and second derivative
              of left and right polynomial are identical at x=0:
              see derivation in function regRoot2
           */
             w :=x2/x1;
             y0d := ( (3*y2 - x2*y2d)/w - (3*y1 - x1*y1d)*w) /(2*x1*(1 - w));
          end if;

          /* Modify derivative y0d, such that the polynomial is
           monotonically increasing. A sufficient condition is
             0 <= y0d <= sqrt(5)*k_i*|x_i|
        */
          w1 :=sqrt(5)*k1*x1;
          w2 :=sqrt(5)*k2*abs(x2);
          // y0d :=min(y0d, 0.9*min(w1, w2));
          ww :=0.9*(if w1 < w2 then w1 else w2);
          if ww < y0d then
             y0d :=ww;
          end if;
          y := if x >= 0 then evaluatePoly3_derivativeAtZero(x,x1,y1,y1d,y0d) else
                              evaluatePoly3_derivativeAtZero(x,x2,y2,y2d,y0d);
       end if;
    end regSquare2_utility;
  algorithm
    y := smooth(2,if x >= x_small then k1*x^2 else
                  if x <= -x_small then -k2*x^2 else
                  if k1 >= k2 then regSquare2_utility(x,x_small,k1,k2,use_yd0,yd0) else
                                  -regSquare2_utility(-x,x_small,k2,k1,use_yd0,yd0));
  end regSquare2;

  function regStep
    "Approximation of a general step, such that the characteristic is continuous and differentiable"
    extends Modelica.Icons.Function;
    input Real x "Abscissa value";
    input Real y1 "Ordinate value for x > 0";
    input Real y2 "Ordinate value for x < 0";
    input Real x_small(min=0) = 1e-5
      "Approximation of step for -x_small <= x <= x_small; x_small >= 0 required";
    output Real y "Ordinate value to approximate y = if x > 0 then y1 else y2";
  algorithm
    y := smooth(1, if x >  x_small then y1 else
                   if x < -x_small then y2 else
                   if x_small > 0 then (x/x_small)*((x/x_small)^2 - 3)*(y2-y1)/4 + (y1+y2)/2 else (y1+y2)/2);

In the region -x_small < x < x_small a 2nd order polynomial is used
for a smooth transition from y1 to y2.

"));
  end regStep;

  function evaluatePoly3_derivativeAtZero
    "Evaluate polynomial of order 3 that passes the origin with a predefined derivative"
    extends Modelica.Icons.Function;
    input Real x "Value for which polynomial shall be evaluated";
    input Real x1 "Abscissa value";
    input Real y1 "y1=f(x1)";
    input Real y1d "First derivative at y1";
    input Real y0d "First derivative at f(x=0)";
    output Real y;
  protected
    Real a1;
    Real a2;
    Real a3;
    Real xx;
  algorithm
    a1 := x1*y0d;
    a2 := 3*y1 - x1*y1d - 2*a1;
    a3 := y1 - a2 - a1;
    xx := x/x1;
    y  := xx*(a1 + xx*(a2 + xx*a3));
  end evaluatePoly3_derivativeAtZero;

  function regFun3 "Co-monotonic and C1 smooth regularization function"
    extends Modelica.Icons.Function;

    input Real x "Abscissa value";
    input Real x0 "Lower abscissa value";
    input Real x1 "Upper abscissa value";
    input Real y0 "Ordinate value at lower abscissa value";
    input Real y1 "Ordinate value at upper abscissa value";
    input Real y0d "Derivative at lower abscissa value";
    input Real y1d "Derivative at upper abscissa value";

    output Real y "Ordinate value";
    output Real c
      "Slope of linear section between two cubic polynomials or dummy linear section slope if single cubic is used";

  protected
    Real h0 "Width of interval i=0";
    Real Delta0 "Slope of secant on interval i=0";
    Real xstar "Inflection point of cubic polynomial S0";
    Real mu "Distance of inflection point and left limit x0";
    Real eta "Distance of right limit x1 and inflection point";
    Real omega "Slope of cubic polynomial S0 at inflection point";
    Real rho "Weighting factor of eta and eta_tilde, mu and mu_tilde";
    Real theta0 "Slope metric";
    Real mu_tilde "Distance of start of linear section and left limit x0";
    Real eta_tilde "Distance of right limit x1 and end of linear section";
    Real xi1 "Start of linear section";
    Real xi2 "End of linear section";
    Real a1 "Leading coefficient of cubic on the left";
    Real a2 "Leading coefficient of cubic on the right";
    Real const12 "Integration constant of left cubic, linear section";
    Real const3 "Integration constant of right cubic";
    Real aux01;
    Real aux02;
    Boolean useSingleCubicPolynomial=false
      "Indicate to override further logic and use single cubic";
  algorithm
    // Check arguments: Data point position
    assert(x0 < x1, "regFun3(): Data points not sorted appropriately (x0 = " +
      String(x0) + " > x1 = " + String(x1) + "). Please flip arguments.");
    // Check arguments: Data point derivatives
    if y0d*y1d >= 0 then
      // Derivatives at data points allow co-monotone interpolation, nothing to do
    else
      // Strictly speaking, derivatives at data points do not allow co-monotone interpolation, however, they may be numerically zero so assert this
      assert(abs(y0d)<Modelica.Constants.eps or abs(y1d)<Modelica.Constants.eps, "regFun3(): Derivatives at data points do not allow co-monotone interpolation, as both are non-zero, of opposite sign and have an absolute value larger than machine eps (y0d = " +
      String(y0d) + ", y1d = " + String(y1d) + "). Please correct arguments.");
    end if;

    h0 := x1 - x0;
    Delta0 := (y1 - y0)/h0;

    if abs(Delta0) <= 0 then
      // Points (x0,y0) and (x1,y1) on horizontal line
      // Degenerate case as we cannot fulfill the C1 goal an comonotone behaviour at the same time
      y := y0 + Delta0*(x-x0);     // y == y0 == y1 with additional term to assist automatic differentiation
      c := 0;
    elseif abs(y1d + y0d - 2*Delta0) < 100*Modelica.Constants.eps then
      // Inflection point at +/- infinity, thus S0 is co-monotone and can be returned directly
      y := y0 + (x-x0)*(y0d + (x-x0)/h0*( (-2*y0d-y1d+3*Delta0) + (x-x0)*(y0d+y1d-2*Delta0)/h0));
      // Provide a "dummy linear section slope" as the slope of the cubic at x:=(x0+x1)/2
      aux01 := (x0 + x1)/2;
      c := 3*(y0d + y1d - 2*Delta0)*(aux01 - x0)^2/h0^2 + 2*(-2*y0d - y1d + 3*Delta0)*(aux01 - x0)/h0
         + y0d;
    else
      // Points (x0,y0) and (x1,y1) not on horizontal line and inflection point of S0 not at +/- infinity
      // Do actual interpolation
      xstar := 1/3*(-3*x0*y0d - 3*x0*y1d + 6*x0*Delta0 - 2*h0*y0d - h0*y1d + 3*h0*
        Delta0)/(-y0d - y1d + 2*Delta0);
      mu := xstar - x0;
      eta := x1 - xstar;
      omega := 3*(y0d + y1d - 2*Delta0)*(xstar - x0)^2/h0^2 + 2*(-2*y0d - y1d + 3*
        Delta0)*(xstar - x0)/h0 + y0d;

      aux01 := 0.25*sign(Delta0)*min(abs(omega), abs(Delta0))
        "Slope c if not using plain cubic S0";
      if abs(y0d - y1d) <= 100*Modelica.Constants.eps then
        // y0 == y1 (value and sign equal) -> resolve indefinite 0/0
        aux02 := y0d;
        if y1 > y0 + y0d*(x1 - x0) then
          // If y1 is above the linear extension through (x0/y0)
          // with slope y0d (when slopes are identical)
          //  -> then always used single cubic polynomial
          useSingleCubicPolynomial := true;
        end if;
      elseif abs(y1d + y0d - 2*Delta0) < 100*Modelica.Constants.eps then
        // (y1d+y0d-2*Delta0) approximately 0 -> avoid division by 0
        aux02 := (6*Delta0*(y1d + y0d - 3/2*Delta0) - y1d*y0d - y1d^2 - y0d^2)*(
          if (y1d + y0d - 2*Delta0) >= 0 then 1 else -1)*Modelica.Constants.inf;
      else
        // Okay, no guarding necessary
        aux02 := (6*Delta0*(y1d + y0d - 3/2*Delta0) - y1d*y0d - y1d^2 - y0d^2)/(3*
          (y1d + y0d - 2*Delta0));
      end if;

      //aux02 := -1/3*(y0d^2+y0d*y1d-6*y0d*Delta0+y1d^2-6*y1d*Delta0+9*Delta0^2)/(y0d+y1d-2*Delta0);
      //aux02 := -1/3*(6*y1d*y0*x1+y0d*y1d*x1^2-6*y0d*x0*y0+y0d^2*x0^2+y0d^2*x1^2+y1d^2*x1^2+y1d^2*x0^2-2*y0d*x0*y1d*x1-2*x0*y0d^2*x1+y0d*y1d*x0^2+6*y0d*x0*y1-6*y0d*y1*x1+6*y0d*y0*x1-2*x0*y1d^2*x1-6*y1d*y1*x1+6*y1d*x0*y1-6*y1d*x0*y0-18*y1*y0+9*y1^2+9*y0^2)/(y0d*x1^2-2*x0*y0d*x1+y1d*x1^2-2*x0*y1d*x1-2*y1*x1+2*y0*x1+y0d*x0^2+y1d*x0^2+2*x0*y1-2*x0*y0);

      // Test criteria (also used to avoid saddle points that lead to integrator contraction):
      //
      //  1. Cubic is not monotonic (from Gasparo Morandi)
      //       ((mu > 0) and (eta < h0) and (Delta0*omega <= 0))
      //
      //  2. Cubic may be monotonic but the linear section slope c is either too close
      //     to zero or the end point of the linear section is left of the start point
      //     Note however, that the suggested slope has to have the same sign as Delta0.
      //       (abs(aux01)<abs(aux02) and aux02*Delta0>=0)
      //
      //  3. Cubic may be monotonic but the resulting slope in the linear section
      //     is too close to zero (less than 1/10 of Delta0).
      //       (c < Delta0 / 10)
      //
      if (((mu > 0) and (eta < h0) and (Delta0*omega <= 0)) or (abs(aux01) < abs(
          aux02) and aux02*Delta0 >= 0) or (abs(aux01) < abs(0.1*Delta0))) and
          not useSingleCubicPolynomial then
        // NOT monotonic using plain cubic S0, use piecewise function S0 tilde instead
        c := aux01;
        // Avoid saddle points that are co-monotonic but lead to integrator contraction
        if abs(c) < abs(aux02) and aux02*Delta0 >= 0 then
          c := aux02;
        end if;
        if abs(c) < abs(0.1*Delta0) then
          c := 0.1*Delta0;
        end if;
        theta0 := (y0d*mu + y1d*eta)/h0;
        if abs(theta0 - c) < 1e-6 then
          // Slightly reduce c in order to avoid ill-posed problem
          c := (1 - 1e-6)*theta0;
        end if;
        rho := 3*(Delta0 - c)/(theta0 - c);
        mu_tilde := rho*mu;
        eta_tilde := rho*eta;
        xi1 := x0 + mu_tilde;
        xi2 := x1 - eta_tilde;
        if  xi1 < x0 or xi2>x1 then
          // The limits don't make sense, just use linear interpolation
          y := (y1-y0)*(x-x0)/(x1-x0) + y0;
        else
          a1 := (y0d - c)/max(mu_tilde^2, 100*Modelica.Constants.eps);
          a2 := (y1d - c)/max(eta_tilde^2, 100*Modelica.Constants.eps);
          const12 := y0 - a1/3*(x0 - xi1)^3 - c*x0;
          const3 := y1 - a2/3*(x1 - xi2)^3 - c*x1;
          // Do actual interpolation
          if (x < xi1) then
            y := a1/3*(x - xi1)^3 + c*x + const12;
          elseif (x < xi2) then
            y := c*x + const12;
          else
            y := a2/3*(x - xi2)^3 + c*x + const3;
          end if;
        end if;
      else
        // Cubic S0 is monotonic, use it as is
        y := y0 + (x-x0)*(y0d + (x-x0)/h0*( (-2*y0d-y1d+3*Delta0) + (x-x0)*(y0d+y1d-2*Delta0)/h0));
        // Provide a "dummy linear section slope" as the slope of the cubic at x:=(x0+x1)/2
        aux01 := (x0 + x1)/2;
        c := 3*(y0d + y1d - 2*Delta0)*(aux01 - x0)^2/h0^2 + 2*(-2*y0d - y1d + 3*Delta0)*(aux01 - x0)/h0
           + y0d;
      end if;
    end if;
  end regFun3;

  function cubicHermite "Evaluate a cubic Hermite spline"
    extends Modelica.Icons.Function;

    input Real x "Abscissa value";
    input Real x1 "Lower abscissa value";
    input Real x2 "Upper abscissa value";
    input Real y1 "Lower ordinate value";
    input Real y2 "Upper ordinate value";
    input Real y1d "Lower gradient";
    input Real y2d "Upper gradient";
    output Real y "Interpolated ordinate value";
  protected
    Real h "Distance between x1 and x2";
    Real t "Abscissa scaled with h, i.e., t=[0..1] within x=[x1..x2]";
    Real h00 "Basis function 00 of cubic Hermite spline";
    Real h10 "Basis function 10 of cubic Hermite spline";
    Real h01 "Basis function 01 of cubic Hermite spline";
    Real h11 "Basis function 11 of cubic Hermite spline";
    Real aux3 "t cube";
    Real aux2 "t square";
  algorithm
    h := x2 - x1;
    if abs(h)>0 then
      // Regular case
      t := (x - x1)/h;

      aux3 :=t^3;
      aux2 :=t^2;

      h00 := 2*aux3 - 3*aux2 + 1;
      h10 := aux3 - 2*aux2 + t;
      h01 := -2*aux3 + 3*aux2;
      h11 := aux3 - aux2;
      y := y1*h00 + h*y1d*h10 + y2*h01 + h*y2d*h11;
    else
      // Degenerate case, x1 and x2 are identical, return step function
      y := (y1 + y2)/2;
    end if;
  end cubicHermite;

  function cubicHermite_withDerivative
    "Evaluate a cubic Hermite spline, return value and derivative"
    extends Modelica.Icons.Function;

    input Real x "Abscissa value";
    input Real x1 "Lower abscissa value";
    input Real x2 "Upper abscissa value";
    input Real y1 "Lower ordinate value";
    input Real y2 "Upper ordinate value";
    input Real y1d "Lower gradient";
    input Real y2d "Upper gradient";
    output Real y "Interpolated ordinate value";
    output Real dy_dx "Derivative dy/dx at abscissa value x";
  protected
    Real h "Distance between x1 and x2";
    Real t "Abscissa scaled with h, i.e., t=[0..1] within x=[x1..x2]";
    Real h00 "Basis function 00 of cubic Hermite spline";
    Real h10 "Basis function 10 of cubic Hermite spline";
    Real h01 "Basis function 01 of cubic Hermite spline";
    Real h11 "Basis function 11 of cubic Hermite spline";

    Real h00d "d/dt h00";
    Real h10d "d/dt h10";
    Real h01d "d/dt h01";
    Real h11d "d/dt h11";

    Real aux3 "t cube";
    Real aux2 "t square";
  algorithm
    h := x2 - x1;
    if abs(h)>0 then
      // Regular case
      t := (x - x1)/h;

      aux3 :=t^3;
      aux2 :=t^2;

      h00 := 2*aux3 - 3*aux2 + 1;
      h10 := aux3 - 2*aux2 + t;
      h01 := -2*aux3 + 3*aux2;
      h11 := aux3 - aux2;

      h00d := 6*(aux2 - t);
      h10d := 3*aux2 - 4*t + 1;
      h01d := 6*(t - aux2);
      h11d := 3*aux2 - 2*t;

      y := y1*h00 + h*y1d*h10 + y2*h01 + h*y2d*h11;
      dy_dx := y1*h00d/h + y1d*h10d + y2*h01d/h + y2d*h11d;
    else
      // Degenerate case, x1 and x2 are identical, return step function
      y := (y1 + y2)/2;
      dy_dx := sign(y2 - y1)*Modelica.Constants.inf;
    end if;
  end cubicHermite_withDerivative;
end Utilities;


within Modelica.Fluid;
package Valves "Components for the regulation and control of fluid flow"
    extends Modelica.Icons.VariantsPackage;

    model ValveIncompressible "Valve for (almost) incompressible fluids"
      extends BaseClasses.PartialValve;
      import Modelica.Fluid.Types.CvTypes;
      import Modelica.Constants.pi;

      constant SI.ReynoldsNumber Re_turbulent = 4000
      "cf. straight pipe for fully open valve -- dp_turbulent increases for closing valve";
      parameter Boolean use_Re = system.use_eps_Re
      "= true, if turbulent region is defined by Re, otherwise by m_flow_small"
      //SI.MassFlowRate m_flow_turbulent=if not use_Re then m_flow_small else
      //  max(m_flow_small,
      //      (Modelica.Constants.pi/8)*sqrt(max(relativeFlowCoefficient,0.001)*Av*4/pi)*(Medium.dynamicViscosity(state_a) + Medium.dynamicViscosity(state_b))*Re_turbulent);
      //SI.AbsolutePressure dp_turbulent_=if not use_Re then dp_small else
      //  max(dp_small, m_flow_turbulent^2/(max(relativeFlowCoefficient,0.001)^2*Av^2*(Medium.density(state_a) + Medium.density(state_b))/2));
      // substitute m_flow_turbulent into dp_turbulent
      SI.AbsolutePressure dp_turbulent = if not use_Re then dp_small else
        max(dp_small, (Medium.dynamicViscosity(state_a) + Medium.dynamicViscosity(state_b))^2*pi/8*Re_turbulent^2
                      /(max(relativeFlowCoefficient,0.001)*Av*(Medium.density(state_a) + Medium.density(state_b))));

  protected
      Real relativeFlowCoefficient;
    initial equation
      if CvData == CvTypes.OpPoint then
          m_flow_nominal = valveCharacteristic(opening_nominal)*Av*sqrt(rho_nominal)*Utilities.regRoot(dp_nominal, dp_small)
        "Determination of Av by the operating point";
      end if;

    equation
      // m_flow = valveCharacteristic(opening)*Av*sqrt(d)*sqrt(dp);

      relativeFlowCoefficient = valveCharacteristic(opening_actual);
      if checkValve then
        m_flow = homotopy(relativeFlowCoefficient*Av*sqrt(Medium.density(state_a))*
                               Utilities.regRoot2(dp,dp_turbulent,1.0,0.0,use_yd0=true,yd0=0.0),
                          relativeFlowCoefficient*m_flow_nominal*dp/dp_nominal);
        /* In Modelica 3.1 (Disadvantage: Unnecessary event at dp=0, and instead of smooth=2)
    m_flow = valveCharacteristic(opening)*Av*sqrt(Medium.density(state_a))*
                  (if dp>=0 then Utilities.regRoot(dp, dp_turbulent) else 0);
    */
      elseif not allowFlowReversal then
        m_flow = homotopy(relativeFlowCoefficient*Av*sqrt(Medium.density(state_a))*
                               Utilities.regRoot(dp, dp_turbulent),
                          relativeFlowCoefficient*m_flow_nominal*dp/dp_nominal);
      else
        m_flow = homotopy(relativeFlowCoefficient*Av*
                               Utilities.regRoot2(dp,dp_turbulent,Medium.density(state_a),Medium.density(state_b)),
                          relativeFlowCoefficient*m_flow_nominal*dp/dp_nominal);
        /* In Modelica 3.1 (Disadvantage: Unnecessary event at dp=0, and instead of smooth=2)
    m_flow = smooth(0, Utilities.regRoot(dp, dp_turbulent)*(if dp>=0 then sqrt(Medium.density(state_a)) else sqrt(Medium.density(state_b))));
    */
      end if;
    end ValveIncompressible;

  model ValveVaporizing
    "Valve for possibly vaporizing (almost) incompressible fluids, accounts for choked flow conditions"
    import Modelica.Fluid.Types.CvTypes;
    import Modelica.Constants.pi;
    extends BaseClasses.PartialValve(
      redeclare replaceable package Medium =
          Modelica.Media.Water.WaterIF97_ph                                    constrainedby
        Modelica.Media.Interfaces.PartialTwoPhaseMedium);
    parameter Real Fl_nominal=0.9 "Liquid pressure recovery factor";
    replaceable function FlCharacteristic =
        Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.one
      constrainedby
      Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.baseFun
      "Pressure recovery characteristic";
    Real Ff "Ff coefficient (see IEC/ISA standard)";
    Real Fl "Pressure recovery coefficient Fl (see IEC/ISA standard)";
    SI.Pressure dpEff "Effective pressure drop";
    Medium.Temperature T_in "Inlet temperature";
    Medium.AbsolutePressure p_sat "Saturation pressure";
    Medium.AbsolutePressure p_in "Inlet pressure";
    Medium.AbsolutePressure p_out "Outlet pressure";

    constant SI.ReynoldsNumber Re_turbulent = 4000
      "cf. straight pipe for fully open valve -- dp_turbulent increases for closing valve";
    parameter Boolean use_Re = system.use_eps_Re
      "= true, if turbulent region is defined by Re, otherwise by m_flow_small"
    //SI.Diameter diameter = Utilities.regRoot(4/pi*valveCharacteristic(opening_actual)*Av, 0.04/pi*valveCharacteristic(opening_nominal)*Av);
    SI.AbsolutePressure dp_turbulent = if not use_Re then dp_small else
      max(dp_small, (Medium.dynamicViscosity(state_a) + Medium.dynamicViscosity(state_b))^2*pi/8*Re_turbulent^2
                    /(valveCharacteristic(opening_actual)*Av*(Medium.density(state_a) + Medium.density(state_b))));
  initial equation
    assert(not CvData == CvTypes.OpPoint, "OpPoint option not supported for vaporizing valve");
  equation
    p_in = port_a.p;
    p_out = port_b.p;
    T_in = Medium.temperature(state_a);
    p_sat = Medium.saturationPressure(T_in);
    Ff = 0.96 - 0.28*sqrt(p_sat/Medium.fluidConstants[1].criticalPressure);
    Fl = Fl_nominal*FlCharacteristic(opening_actual);
    dpEff = if p_out < (1 - Fl^2)*p_in + Ff*Fl^2*p_sat then
              Fl^2*(p_in - Ff*p_sat) else dp
      "Effective pressure drop, accounting for possible choked conditions";
    // m_flow = valveCharacteristic(opening)*Av*sqrt(d)*sqrt(dpEff);
    if checkValve then
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*sqrt(Medium.density(state_a))*
                             Utilities.regRoot2(dpEff,dp_turbulent,1.0,0.0,use_yd0=true,yd0=0.0),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
     /* In Modelica 3.1 (Disadvantage: Unnecessary event at dpEff=0, and instead of smooth=2)
    m_flow = valveCharacteristic(opening)*Av*sqrt(Medium.density(state_a))*
                  (if dpEff>=0 then Utilities.regRoot(dpEff, dp_turbulent) else 0);
   */
    elseif not allowFlowReversal then
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*sqrt(Medium.density(state_a))*
                             Utilities.regRoot(dpEff, dp_turbulent),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
    else
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*
                             Utilities.regRoot2(dpEff,dp_turbulent,Medium.density(state_a),Medium.density(state_b)),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
      /* In Modelica 3.1 (Disadvantage: Unnecessary event at dp=0, and instead of smooth=2)
     m_flow = valveCharacteristic(opening)*Av*
      smooth(0, Utilities.regRoot(dpEff, dp_turbulent)*(if dpEff>=0 then sqrt(Medium.density(state_a)) else sqrt(Medium.density(state_b))));
   */
    end if;
  end ValveVaporizing;

  model ValveCompressible
    "Valve for compressible fluids, accounts for choked flow conditions"
    extends BaseClasses.PartialValve;
    import Modelica.Fluid.Types.CvTypes;
    import Modelica.Constants.pi;
    parameter Medium.AbsolutePressure p_nominal "Nominal inlet pressure"
    parameter Real Fxt_full=0.5 "Fk*xt critical ratio at full opening";
    replaceable function xtCharacteristic =
        Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.one
      constrainedby
      Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.baseFun
      "Critical ratio characteristic";
    Real Fxt;
    Real x "Pressure drop ratio";
    Real xs "Saturated pressure drop ratio";
    Real Y "Compressibility factor";
    Medium.AbsolutePressure p "Inlet pressure";

    constant SI.ReynoldsNumber Re_turbulent = 4000
      "cf. straight pipe for fully open valve -- dp_turbulent increases for closing valve";
    parameter Boolean use_Re = system.use_eps_Re
      "= true, if turbulent region is defined by Re, otherwise by m_flow_small"
    SI.AbsolutePressure dp_turbulent = if not use_Re then dp_small else
      max(dp_small, (Medium.dynamicViscosity(state_a) + Medium.dynamicViscosity(state_b))^2*pi/8*Re_turbulent^2
                    /(max(valveCharacteristic(opening_actual),0.001)*Av*Y*(Medium.density(state_a) + Medium.density(state_b))));
  protected
    parameter Real Fxt_nominal(fixed=false) "Nominal Fxt";
    parameter Real x_nominal(fixed=false) "Nominal pressure drop ratio";
    parameter Real xs_nominal(fixed=false)
      "Nominal saturated pressure drop ratio";
    parameter Real Y_nominal(fixed=false) "Nominal compressibility factor";

  initial equation
    if CvData == CvTypes.OpPoint then
      // Determination of Av by the nominal operating point conditions
      Fxt_nominal = Fxt_full*xtCharacteristic(opening_nominal);
      x_nominal = dp_nominal/p_nominal;
      xs_nominal = smooth(0, if x_nominal > Fxt_nominal then Fxt_nominal else x_nominal);
      Y_nominal = 1 - abs(xs_nominal)/(3*Fxt_nominal);
      m_flow_nominal = valveCharacteristic(opening_nominal)*Av*Y_nominal*sqrt(rho_nominal)*Utilities.regRoot(p_nominal*xs_nominal, dp_small);
    else
      // Dummy values
      Fxt_nominal = 0;
      x_nominal = 0;
      xs_nominal = 0;
      Y_nominal = 0;
    end if;

  equation
    p = max(port_a.p, port_b.p);
    Fxt = Fxt_full*xtCharacteristic(opening_actual);
    x = dp/p;
    xs = max(-Fxt, min(x, Fxt));
    Y = 1 - abs(xs)/(3*Fxt);
    // m_flow = valveCharacteristic(opening)*Av*Y*sqrt(d)*sqrt(p*xs);
    if checkValve then
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*Y*sqrt(Medium.density(state_a))*
                             (if xs>=0 then Utilities.regRoot(p*xs, dp_turbulent) else 0),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
    elseif not allowFlowReversal then
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*Y*sqrt(Medium.density(state_a))*
                             Utilities.regRoot(p*xs, dp_turbulent),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
    else
      m_flow = homotopy(valveCharacteristic(opening_actual)*Av*Y*
                             Utilities.regRoot2(p*xs, dp_turbulent, Medium.density(state_a), Medium.density(state_b)),
                        valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
  /* alternative formulation using smooth(0, ...) -- should not be used as regRoot2 has continuous derivatives
   -- cf. ModelicaTest.Fluid.TestPipesAndValves.DynamicPipeInitialization --
    m_flow = homotopy(valveCharacteristic(opening_actual)*Av*Y*
                        smooth(0, Utilities.regRoot(p*xs, dp_turbulent)*
                        (if xs>=0 then sqrt(Medium.density(state_a)) else sqrt(Medium.density(state_b)))),
                      valveCharacteristic(opening_actual)*m_flow_nominal*dp/dp_nominal);
*/
    end if;
  end ValveCompressible;

  model ValveLinear "Valve for water/steam flows with linear pressure drop"
    extends Modelica.Fluid.Interfaces.PartialTwoPortTransport;
    parameter SI.AbsolutePressure dp_nominal
      "Nominal pressure drop at full opening"
    parameter Medium.MassFlowRate m_flow_nominal
      "Nominal mass flowrate at full opening";
    final parameter Types.HydraulicConductance k = m_flow_nominal/dp_nominal
      "Hydraulic conductance at full opening";
    Modelica.Blocks.Interfaces.RealInput opening(min=0,max=1)
      "=1: completely open, =0: completely closed"

  equation
    m_flow = opening*k*dp;

    // Isenthalpic state transformation (no storage and no loss of energy)
    port_a.h_outflow = inStream(port_b.h_outflow);
    port_b.h_outflow = inStream(port_a.h_outflow);
  end ValveLinear;

  model ValveDiscrete "Valve for water/steam flows with linear pressure drop"
    extends Modelica.Fluid.Interfaces.PartialTwoPortTransport;
    parameter SI.AbsolutePressure dp_nominal
      "Nominal pressure drop at full opening=1"
    parameter Medium.MassFlowRate m_flow_nominal
      "Nominal mass flowrate at full opening=1";
    final parameter Types.HydraulicConductance k = m_flow_nominal/dp_nominal
      "Hydraulic conductance at full opening=1";
    Modelica.Blocks.Interfaces.BooleanInput open
    parameter Real opening_min(min=0)=0
      "Remaining opening if closed, causing small leakage flow";
  equation
    m_flow = if open then 1*k*dp else opening_min*k*dp;

    // Isenthalpic state transformation (no storage and no loss of energy)
    port_a.h_outflow = inStream(port_b.h_outflow);
    port_b.h_outflow = inStream(port_a.h_outflow);
  end ValveDiscrete;

  model ValveDiscreteRamp
    "Valve for water/steam flows with discrete opening signal and ramp opening"
    extends Modelica.Fluid.Interfaces.PartialTwoPortTransport;
    parameter SI.AbsolutePressure dp_nominal
      "Nominal pressure drop at full opening"
    parameter Medium.MassFlowRate m_flow_nominal
      "Nominal mass flowrate at full opening";
    parameter Real opening_min(min=0)=0
      "Remaining opening if closed, causing small leakage flow";
    final parameter Types.HydraulicConductance k = m_flow_nominal/dp_nominal
      "Hydraulic conductance at full opening";
    parameter SI.Time Topen "Time to fully open the valve";
    parameter SI.Time Tclose = Topen "Time to fully close the valve";

    Modelica.Blocks.Interfaces.BooleanInput open
    Blocks.Logical.TriggeredTrapezoid openingGenerator(
      amplitude=1 - opening_min,                       rising=Topen, falling=
          Tclose,
      offset=opening_min)

  equation
    m_flow = openingGenerator.y*k*dp;

    // Isenthalpic state transformation (no storage and no loss of energy)
    port_a.h_outflow = inStream(port_b.h_outflow);
    port_b.h_outflow = inStream(port_a.h_outflow);
    connect(open, openingGenerator.u)
  end ValveDiscreteRamp;

  package BaseClasses
    "Base classes used in the Valves package (only of interest to build new component models)"
    extends Modelica.Icons.BasesPackage;
    partial model PartialValve "Base model for valves"

      import Modelica.Fluid.Types.CvTypes;
      extends Modelica.Fluid.Interfaces.PartialTwoPortTransport(
        dp_start = dp_nominal,
        m_flow_small = if system.use_eps_Re then system.eps_m_flow*m_flow_nominal else system.m_flow_small,
        m_flow_start = m_flow_nominal);

      parameter Modelica.Fluid.Types.CvTypes CvData=Modelica.Fluid.Types.CvTypes.OpPoint
        "Selection of flow coefficient"
      parameter SI.Area Av(
        fixed= CvData == Modelica.Fluid.Types.CvTypes.Av,
        start=m_flow_nominal/(sqrt(rho_nominal*dp_nominal))*valveCharacteristic(
            opening_nominal)) "Av (metric) flow coefficient"
      parameter Real Kv = 0 "Kv (metric) flow coefficient [m3/h]"
      parameter Real Cv = 0 "Cv (US) flow coefficient [USG/min]"
      parameter SI.Pressure dp_nominal "Nominal pressure drop"
      parameter Medium.MassFlowRate m_flow_nominal "Nominal mass flowrate"
      parameter Medium.Density rho_nominal=Medium.density_pTX(Medium.p_default, Medium.T_default, Medium.X_default)
        "Nominal inlet density"
      parameter Real opening_nominal(min=0,max=1)=1 "Nominal opening"

      parameter Boolean filteredOpening=false
        "= true, if opening is filtered with a 2nd order CriticalDamping filter"
      parameter SI.Time riseTime=1
        "Rise time of the filter (time to reach 99.6 % of an opening step)"
      parameter Real leakageOpening(min=0,max=1)=1e-3
        "The opening signal is limited by leakageOpening (to improve the numerics)"
      parameter Boolean checkValve=false "Reverse flow stopped"

      replaceable function valveCharacteristic =
          Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.linear
        constrainedby
        Modelica.Fluid.Valves.BaseClasses.ValveCharacteristics.baseFun
        "Inherent flow characteristic"
    protected
      parameter SI.Pressure dp_small=if system.use_eps_Re then dp_nominal/m_flow_nominal*m_flow_small else system.dp_small
        "Regularisation of zero flow"

    public
      constant SI.Area Kv2Av = 27.7e-6 "Conversion factor";
      constant SI.Area Cv2Av = 24.0e-6 "Conversion factor";

      Modelica.Blocks.Interfaces.RealInput opening(min=0, max=1)
        "Valve position in the range 0..1"

      Modelica.Blocks.Interfaces.RealOutput opening_filtered if filteredOpening
        "Filtered valve position in the range 0..1"

      Modelica.Blocks.Continuous.Filter filter(order=2, f_cut=5/(2*Modelica.Constants.pi
            *riseTime)) if filteredOpening

    protected
      Modelica.Blocks.Interfaces.RealOutput opening_actual

    block MinLimiter "Limit the signal above a threshold"
     parameter Real uMin=0 "Lower limit of input signal";
      extends Modelica.Blocks.Interfaces.SISO;

    equation
      y = smooth(0, noEvent( if u < uMin then uMin else u));
    end MinLimiter;

      MinLimiter minLimiter(uMin=leakageOpening)
    initial equation
      if CvData == CvTypes.Kv then
        Av = Kv*Kv2Av "Unit conversion";
      elseif CvData == CvTypes.Cv then
        Av = Cv*Cv2Av "Unit conversion";
      end if;

    equation
      // Isenthalpic state transformation (no storage and no loss of energy)
      port_a.h_outflow = inStream(port_b.h_outflow);
      port_b.h_outflow = inStream(port_a.h_outflow);

      connect(filter.y, opening_filtered)

      if filteredOpening then
         connect(filter.y, opening_actual);
      else
         connect(opening, opening_actual);
      end if;

      connect(minLimiter.y, filter.u)
      connect(minLimiter.u, opening) changes in kinetic energy
from inlet to outlet are neglected in the energy balance.

Modelling options

The following options are available to specify the valve flow coefficient in fully open conditions:

CvData = Modelica.Fluid.Types.CvTypes.Av: the flow coefficient is given by the metric Av coefficient (m^2).

CvData = Modelica.Fluid.Types.CvTypes.Kv: the flow coefficient is given by the metric Kv coefficient (m^3/h).

CvData = Modelica.Fluid.Types.CvTypes.Cv: the flow coefficient is given by the US Cv coefficient (USG/min).

CvData = Modelica.Fluid.Types.CvTypes.OpPoint: the flow is computed from the nominal operating point specified by p_nominal, dp_nominal, m_flow_nominal, rho_nominal, opening_nominal.

The nominal pressure drop dp_nominal must always be specified; to avoid numerical singularities, the flow characteristic is modified for pressure drops less than b*dp_nominal (the default value is 1% of the nominal pressure drop). Increase this parameter if numerical problems occur in valves with very low pressure drops.

If checkValve is true, then the flow is stopped when the outlet pressure is higher than the inlet pressure; otherwise, reverse flow takes place. Use this option only when needed, as it increases the numerical complexity of the problem.

The valve opening characteristic valveCharacteristic, linear by default, can be replaced by any user-defined function. Quadratic and equal percentage with customizable rangeability are already provided by the library. The characteristics for constant port_a.p and port_b.p pressures with continuously changing opening are shown in the next two figures:

The treatment of parameters Kv and Cv is
explained in detail in the
User's Guide.

With the optional parameter \"filteredOpening\", the opening can be filtered with a
second order, criticalDamping filter so that the
opening demand is delayed by parameter \"riseTime\". The filtered opening is then available
via the output signal \"opening_filtered\" and is used to control the valve equations.
This approach approximates the driving device of a valve. The \"riseTime\" parameter
is used to compute the cut-off frequency of the filter by the equation: f_cut = 5/(2*pi*riseTime).
It defines the time that is needed until opening_filtered reaches 99.6 % of
a step input of opening. The icon of a valve changes in the following way
(left image: filteredOpening=false, right image: filteredOpening=true):

If \"filteredOpening = true\", the input signal \"opening\" is limited
by parameter leakageOpening, i.e., if \"opening\" becomes smaller as
\"leakageOpening\", then \"leakageOpening\" is used instead of \"opening\" as input
for the filter. The reason is that \"opening=0\" might structurally change the equations of the
fluid network leading to a singularity. If a small leakage flow is introduced
(which is often anyway present in reality), the singularity might be avoided.

In the next figure, \"opening\" and \"filtered_opening\" are shown in the case that
filteredOpening = true, riseTime = 1 s, and leakageOpening = 0.02.

", revisions="

Sept. 5, 2010
    by Martin Otter:

    Optional filtering of opening introduced, based on a proposal
    from Mike Barth (Universitaet der Bundeswehr Hamburg) +
    Documentation improved.

2 Nov 2005
    by Francesco Casella:

       Adapted from the ThermoPower library.

"));
    end PartialValve;

  package ValveCharacteristics "Functions for valve characteristics"
    extends Modelica.Icons.VariantsPackage;
    partial function baseFun "Base class for valve characteristics"
      extends Modelica.Icons.Function;
      input Real pos(min=0, max=1)
          "Opening position (0: closed, 1: fully open)";
      output Real rc "Relative flow coefficient (per unit)";
    end baseFun;

    function linear "Linear characteristic"
      extends baseFun;
    algorithm
      rc := pos;
    end linear;

    function one "Constant characteristic"
      extends baseFun;
    algorithm
      rc := 1;
    end one;

    function quadratic "Quadratic characteristic"
      extends baseFun;
    algorithm
      rc := pos*pos;
    end quadratic;

    function equalPercentage "Equal percentage characteristic"
      extends baseFun;
      input Real rangeability = 20 "Rangeability"
      input Real delta = 0.01
    algorithm
      rc := if pos > delta then rangeability^(pos-1) else
              pos/delta*rangeability^(delta-1);
    end equalPercentage;

  end ValveCharacteristics;
  end BaseClasses;
end Valves;