/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | Multiphase Code Repository by HZDR
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.767
  ||  ||  //    ||  // || \\   | License: GPL-3.0-or-later
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
License
    This file is part of the Multiphase Code Repository by HZDR.

    Copyright (C) 2025 by Helmholtz-Zentrum Dresden-Rossendorf e.V. (HZDR),
    Website: https://hzdr.de

    Multiphase Code Repository by HZDR is based on the free software for
    computational fluid dynamics (CFD) from the OpenFOAM Foundation.
    Copyright (C) 2025 by OpenFOAM Foundation, Website: https://openfoam.org

    If you are interested in which files are original OpenFOAM Foundation
    files, which OpenFOAM Foundation files were modified, and which files were
    newly created, see FILES.md.

    Multiphase Code Repository by HZDR is free software: you can redistribute
    it and/or modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    Multiphase Code Repository by HZDR is distributed in the hope that it will
    be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
    Public License for more details.

    You should have received a copy of the GNU General Public License along
    with the Multiphase Code Repository by HZDR. If not, see
    <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "PIDcontrolledInletVelocityFvPatchVectorField.H"
#include "uniformDimensionedFields.H"
#include "addToRunTimeSelectionTable.H"

// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::PIDcontrolledInletVelocityFvPatchVectorField::
PIDcontrolledInletVelocityFvPatchVectorField
(
    const fvPatch& p,
    const DimensionedField<vector, volMesh>& iF,
    const dictionary& dict
)
:
    fixedValueFvPatchVectorField(p, iF, dict),

    controlVarName_(dict.lookup("controlVar")),
    targetPos_(dimLength, dict.lookup("targetPos")),

    kP_(inv(dimTime), dict.lookupOrDefault<vector>("kP", vector::zero)),
    kI_(inv(sqr(dimTime)), dict.lookupOrDefault<vector>("kI", vector::zero)),
    kD_(dimless, dict.lookupOrDefault<vector>("kD", vector::zero)),

    relaxationFactor_
    (
        dict.lookupOrDefault<scalar>("relaxationFactor", dimless, 1)
    ),

    deviation_
    (
        dimLength,
        dict.lookupOrDefault<vector>("deviation", vector::zero)
    ),
    deviation0_(dimLength, vector::zero),
    timeIndex0_
    (
        dict.lookupOrDefault("timeIndex0", this->db().time().timeIndex())
    ),

    uI_
    (
        dimVelocity,
        dict.lookupOrDefault<vector>("uI", vector::zero)
    )
{}


Foam::PIDcontrolledInletVelocityFvPatchVectorField::
PIDcontrolledInletVelocityFvPatchVectorField
(
    const PIDcontrolledInletVelocityFvPatchVectorField& ptf,
    const fvPatch& p,
    const DimensionedField<vector, volMesh>& iF,
    const fieldMapper& mapper
)
:
    fixedValueFvPatchVectorField(ptf, p, iF, mapper),
    controlVarName_(ptf.controlVarName_),
    targetPos_(ptf.targetPos_),
    kP_(ptf.kP_),
    kI_(ptf.kI_),
    kD_(ptf.kD_),
    relaxationFactor_(ptf.relaxationFactor_),
    deviation_(ptf.deviation_),
    deviation0_(ptf.deviation0_),
    timeIndex0_(ptf.timeIndex0_),
    uI_(ptf.uI_)
{}


Foam::PIDcontrolledInletVelocityFvPatchVectorField::
PIDcontrolledInletVelocityFvPatchVectorField
(
    const PIDcontrolledInletVelocityFvPatchVectorField& ptf,
    const DimensionedField<vector, volMesh>& iF
)
:
    fixedValueFvPatchVectorField(ptf, iF),
    controlVarName_(ptf.controlVarName_),
    targetPos_(ptf.targetPos_),
    kP_(ptf.kP_),
    kI_(ptf.kI_),
    kD_(ptf.kD_),
    relaxationFactor_(ptf.relaxationFactor_),
    deviation_(ptf.deviation_),
    deviation0_(ptf.deviation0_),
    timeIndex0_(ptf.timeIndex0_),
    uI_(ptf.uI_)
{}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

void Foam::PIDcontrolledInletVelocityFvPatchVectorField::updateCoeffs()
{
    if (updated())
    {
        return;
    }

    const dimensionedVector& controlVar =
        this->db().lookupObject<uniformDimensionedVectorField>(controlVarName_);

    dimensionedVector deviation(controlVar - targetPos_);

    if (this->db().time().timeIndex() > timeIndex0_)
    {
        deviation0_ = deviation_;
        deviation_ = deviation;

        timeIndex0_ = this->db().time().timeIndex();
    }

    if (0 < relaxationFactor_ && relaxationFactor_ < 1)
    {
        deviation = deviation0_ + relaxationFactor_*(deviation - deviation0_);
    }

    const vector X(vector(1, 0, 0));
    const vector Y(vector(0, 1, 0));
    const vector Z(vector(0, 0, 1));

    // Proportional
    const dimensionedVector uP
    (
        "uP",
        deviation.component(vector::X)*kP_.component(vector::X)*X
      + deviation.component(vector::Y)*kP_.component(vector::Y)*Y
      + deviation.component(vector::Z)*kP_.component(vector::Z)*Z
    );

    // Integral
    uI_ +=
        this->db().time().deltaT()
       *(
           deviation.component(vector::X)*kI_.component(vector::X)*X
         + deviation.component(vector::Y)*kI_.component(vector::Y)*Y
         + deviation.component(vector::Z)*kI_.component(vector::Z)*Z
        );

    // Differential
    const dimensionedVector dDeviation(deviation - deviation0_);
    const dimensionedVector uD
    (
        "uD",
        (
            dDeviation.component(vector::X)*kD_.component(vector::X)*X
          + dDeviation.component(vector::Y)*kD_.component(vector::Y)*Y
          + dDeviation.component(vector::Z)*kD_.component(vector::Z)*Z
        )/this->db().time().deltaT()
    );

    dimensionedVector uPID("uPID", uP + uI_ + uD);
    fvPatchVectorField::operator=(uPID.value());

    fvPatchVectorField::updateCoeffs();
}


void Foam::PIDcontrolledInletVelocityFvPatchVectorField::write
(
    Ostream& os
) const
{
    fvPatchVectorField::write(os);

    writeEntry(os, "controlVar", controlVarName_);
    writeEntry(os, "targetPos", targetPos_.value());

    writeEntryIfDifferent<vector>(os, "kP", vector::zero, kP_.value());
    writeEntryIfDifferent<vector>(os, "kI", vector::zero, kI_.value());
    writeEntryIfDifferent<vector>(os, "kD", vector::zero, kD_.value());

    writeEntryIfDifferent<scalar>(os, "relaxationFactor", 1, relaxationFactor_);

    writeEntry(os, "deviation", deviation_.value());
    writeEntry(os, "timeIndex0", timeIndex0_);

    writeEntry(os, "uI", uI_.value());

    writeEntry(os, "value", *this);
}


// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

namespace Foam
{
   makePatchTypeField
   (
       fvPatchVectorField,
       PIDcontrolledInletVelocityFvPatchVectorField
   );
}


// ************************************************************************* //
