/*---------------------------------------------------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | 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 "SSGManceau.H"
#include "fvModels.H"
#include "fvConstraints.H"
#include "bound.H"

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

namespace Foam
{
namespace RASModels
{

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

template<class BasicMomentumTransportModel>
tmp<volScalarField> SSGManceau<BasicMomentumTransportModel>::L() const
{
    return
        CL_
       *max
        (
            pow(k_, 1.5)/epsilon_,
            CEta_ * pow025(pow3(this->nu())/epsilon_)
        );
}


template<class BasicMomentumTransportModel>
tmp<volScalarField> SSGManceau<BasicMomentumTransportModel>::T() const
{
    return
        max
        (
            k_/epsilon_,
            CT_*sqrt(this->nu()/epsilon_)
        );
}


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

template<class BasicMomentumTransportModel>
tmp<volScalarField> SSGManceau<BasicMomentumTransportModel>::boundEpsilon()
{
    tmp<volScalarField> tCmuk2(Cmu_*sqr(k_));
    epsilon_ = max(epsilon_, tCmuk2()/(this->nutMaxCoeff_*this->nu()));
    return tCmuk2;
}


template<class BasicMomentumTransportModel>
void SSGManceau<BasicMomentumTransportModel>::correctNut()
{
    this->nut_ = boundEpsilon()/epsilon_;
    this->nut_.correctBoundaryConditions();
    fvConstraints::New(this->mesh_).constrain(this->nut_);
}


template<class BasicMomentumTransportModel>
tmp<fvSymmTensorMatrix> SSGManceau<BasicMomentumTransportModel>::RSource() const
{
    return tmp<fvSymmTensorMatrix>
    (
        new fvSymmTensorMatrix
        (
            this->R_,
            dimVolume*this->rho_.dimensions()*this->R_.dimensions()/dimTime
        )
    );
}


template<class BasicMomentumTransportModel>
tmp<fvScalarMatrix>
SSGManceau<BasicMomentumTransportModel>::epsilonSource() const
{
    return tmp<fvScalarMatrix>
    (
        new fvScalarMatrix
        (
            epsilon_,
            dimVolume*this->rho_.dimensions()*epsilon_.dimensions()/dimTime
        )
    );
}


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

template<class BasicMomentumTransportModel>
SSGManceau<BasicMomentumTransportModel>::SSGManceau
(
    const alphaField& alpha,
    const rhoField& rho,
    const volVectorField& U,
    const surfaceScalarField& alphaRhoPhi,
    const surfaceScalarField& phi,
    const viscosity& viscosity,
    const word& type
)
:
    ReynoldsStress<RASModel<BasicMomentumTransportModel>>
    (
        type,
        alpha,
        rho,
        U,
        alphaRhoPhi,
        phi,
        viscosity
    ),

    Cmu_("Cmu", this->coeffDict(), 0.09),
    C1_("C1", this->coeffDict(), 3.4),
    C1s_("C1s", this->coeffDict(), 1.8),
    C2_("C2", this->coeffDict(), 0.0),
    C3_("C3", this->coeffDict(), 0.8),
    C3s_("C3s", this->coeffDict(), 1.3),
    C4_("C4", this->coeffDict(), 1.25),
    C5_("C5", this->coeffDict(), 0.4),

    Ceps1_("Ceps1", this->coeffDict(), 1.44),
    Ceps2_("Ceps2", this->coeffDict(), 1.83),
    Cs_("Cs", this->coeffDict(), 0.21),
    Ceps_("Ceps", this->coeffDict(), 0.183),
    CT_("CT", this->coeffDict(), 6.0),
    CL_("CL", this->coeffDict(), 0.133),
    CEta_("CEta", this->coeffDict(), 80.0),

    k_
    (
        IOobject
        (
            this->groupName("k"),
            this->runTime_.name(),
            this->mesh_,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        0.5*tr(this->R_)
    ),
    epsilon_
    (
        IOobject
        (
            this->groupName("epsilon"),
            this->runTime_.name(),
            this->mesh_,
            IOobject::MUST_READ,
            IOobject::AUTO_WRITE
        ),
        this->mesh_
    ),
    alphaRelax_
    (
        IOobject
        (
            "alphaRelax",
            this->runTime_.name(),
            this->mesh_,
            IOobject::MUST_READ,
            IOobject::AUTO_WRITE
        ),
        this->mesh_
    )
{
    if (type == typeName)
    {
        this->boundNormalStress(this->R_);
        boundEpsilon();
        k_ = 0.5*tr(this->R_);
        correctNut();
    }
}


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

template<class BasicMomentumTransportModel>
bool SSGManceau<BasicMomentumTransportModel>::read()
{
    if (ReynoldsStress<RASModel<BasicMomentumTransportModel>>::read())
    {
        Cmu_.readIfPresent(this->coeffDict());
        C1_.readIfPresent(this->coeffDict());
        C1s_.readIfPresent(this->coeffDict());
        C2_.readIfPresent(this->coeffDict());
        C3_.readIfPresent(this->coeffDict());
        C3s_.readIfPresent(this->coeffDict());
        C4_.readIfPresent(this->coeffDict());
        C5_.readIfPresent(this->coeffDict());

        Ceps1_.readIfPresent(this->coeffDict());
        Ceps2_.readIfPresent(this->coeffDict());
        Cs_.readIfPresent(this->coeffDict());
        Ceps_.readIfPresent(this->coeffDict());

        CT_.readIfPresent(this->coeffDict());
        CL_.readIfPresent(this->coeffDict());
        CEta_.readIfPresent(this->coeffDict());

        return true;
    }
    else
    {
        return false;
    }
}


template<class BasicMomentumTransportModel>
tmp<volSymmTensorField> SSGManceau<BasicMomentumTransportModel>::DREff() const
{
    return volSymmTensorField::New
    (
        "DREff",
        Cs_*T()*this->R_ + I*this->nu()
    );
}


template<class BasicMomentumTransportModel>
tmp<volSymmTensorField> SSGManceau<BasicMomentumTransportModel>::
DepsilonEff() const
{
    return volSymmTensorField::New
    (
        "DepsilonEff",
        Ceps_*T()*this->R_ + I*this->nu()
    );
}


template<class BasicMomentumTransportModel>
void SSGManceau<BasicMomentumTransportModel>::correct()
{
    if (!this->turbulence_)
    {
        return;
    }

    // Local references
    const alphaField& alpha = this->alpha_;
    const rhoField& rho = this->rho_;
    const surfaceScalarField& alphaRhoPhi = this->alphaRhoPhi_;
    const volVectorField& U = this->U_;
    volSymmTensorField& R = this->R_;
    volScalarField Ts("T", T());
    const Foam::fvModels& fvModels(Foam::fvModels::New(this->mesh_));
    const Foam::fvConstraints& fvConstraints
    (
        Foam::fvConstraints::New(this->mesh_)
    );

    ReynoldsStress<RASModel<BasicMomentumTransportModel>>::correct();

    tmp<volTensorField> tgradU(fvc::grad(U));
    const volTensorField& gradU = tgradU();

    volSymmTensorField P(-twoSymm(R & gradU));
    volScalarField G(this->GName(), 0.5*mag(tr(P)));
    volScalarField magP(0.5*mag(tr(P)));

    volVectorField n(fvc::grad(alphaRelax_));
    n /= mag(n) + dimensionedScalar(n.dimensions(), VSMALL);
    volSymmTensorField nn(symm(n*n));

    volScalarField alphaR3(pow(alphaRelax_, 3));
    volScalarField Peps
    (
        Ceps1_*(1 + 0.065*(1 - alphaR3)*magP/epsilon_)*alpha*rho*magP/Ts
    );

    tmp<volSymmTensorField> Psw =
        - 5*(1 - alphaR3)*epsilon_/k_
         *(twoSymm(this->R_ & nn) - 0.5*(this->R_ && nn)*(nn + I));

    // Update epsilon and G at the wall
    epsilon_.boundaryFieldRef().updateCoeffs();

    // Dissipation equation
    tmp<fvScalarMatrix> epsEqn
    (
        fvm::ddt(alpha, rho, epsilon_)
      + fvm::div(alphaRhoPhi, epsilon_)
      - fvm::laplacian(alpha*rho*DepsilonEff(), epsilon_)
     ==
        Peps
      - fvm::Sp(Ceps2_*alpha*rho/Ts, epsilon_)
      + epsilonSource()
      + fvModels.source(alpha, rho, epsilon_)
    );

    epsEqn.ref().relax();
    fvConstraints.constrain(epsEqn.ref());
    epsEqn.ref().boundaryManipulate(epsilon_.boundaryFieldRef());
    solve(epsEqn);
    fvConstraints.constrain(epsilon_);
    boundEpsilon();


    volSymmTensorField b(dev(R)/(2*k_));
    volSymmTensorField S(symm(gradU));
    volTensorField Omega(skew(gradU));

    // Reynolds stress equation
    tmp<fvSymmTensorMatrix> REqn
    (
        fvm::ddt(alpha, rho, R)
      + fvm::div(alphaRhoPhi, R)
      - fvm::laplacian(alpha*rho*DREff(), R)
      + fvm::Sp(alphaR3*((C1_/2)*epsilon_ + (C1s_/2)*magP)*alpha*rho/k_, R)
      + fvm::Sp((1 - alphaR3)*alpha*rho*epsilon_/k_, R)
     ==
        alpha*rho*P
      - alphaR3*((1.0/3.0)*I)*(((2 - C1_)*epsilon_ - C1s_*magP)*alpha*rho)
      + alphaR3*(C2_*(alpha*rho*epsilon_))*dev(innerSqr(b))
      + alphaR3*alpha*rho*k_
       *(
            (C3_ - C3s_*mag(b))*dev(S)
          + C4_*dev(twoSymm(b&S))
          + C5_*twoSymm(b&Omega)
        )
      + alpha*rho*Psw
      + this->RSource()
      + fvModels.source(alpha, rho, R)
    );

    REqn.ref().relax();
    fvConstraints.constrain(REqn.ref());
    solve(REqn);
    fvConstraints.constrain(R);

    this->boundNormalStress(R);

    k_ = 0.5*tr(R);

    volScalarField rSqrL(1/sqr(L()));

    // Elliptic equation to solve for blending parameter used to blend the SSG
    // model with the near-wall treatment
    tmp<fvScalarMatrix> alphaRelaxEqn
    (
        fvm::laplacian(alphaRelax_)
     ==
        fvm::Sp(rSqrL, alphaRelax_)
      - rSqrL
    );

    alphaRelaxEqn.ref().relax();
    solve(alphaRelaxEqn);

    alphaRelax_ = min(max(Zero, alphaRelax_), scalar(1.0));

    correctNut();

    // Correct wall shear-stresses when applying wall-functions
    this->correctWallShearStress(R);
}


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

} // End namespace RASModels
} // End namespace Foam

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