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

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

namespace Foam
{

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

template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::ReT() const
{
    return k_/(this->nu()*omega_);
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::alphaStarOne() const
{
    return (alphaStar0_*RK_ + ReT())/(RK_ + ReT());
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::alphaOne() const
{
    return 5.0/9.0*(alpha0_*ROmega_ + ReT())/(alphaStarOne()*(ROmega_ + ReT()));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::betaStarOne() const
{
    return (0.025 + 0.09*pow4(ReT()/RBeta_))/(1 + pow4(ReT()/RBeta_));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::F1
(
    const volScalarField& CDkOmega
) const
{
    tmp<volScalarField> CDkOmegaPlus = max
    (
        CDkOmega,
        dimensionedScalar(dimless/sqr(dimTime), 1.0e-10)
    );

    tmp<volScalarField> arg1 = min
    (
        min
        (
            max
            (
                (scalar(1)/scalar(0.09))*sqrt(k_)/(omega_*y_),
                scalar(500)*this->nu()/(sqr(y_)*omega_)
            ),
            (4*alphaOmega2_)*k_/(CDkOmegaPlus*sqr(y_))
        ),
        scalar(10)
    );

    return tanh(pow4(arg1));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::F2() const
{
    tmp<volScalarField> arg2 = min
    (
        max
        (
            (scalar(2)/scalar(0.09))*sqrt(k_)/(omega_*y_),
            scalar(500)*this->nu()/(sqr(y_)*omega_)
        ),
        scalar(100)
    );

    return tanh(sqr(arg2));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::F3() const
{
    tmp<volScalarField> arg3 = min
    (
        150*this->nu()/(omega_*sqr(y_)),
        scalar(10)
    );

    return 1 - tanh(pow4(arg3));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kOmegaSSTLangtrySjolander::F23() const
{
    tmp<volScalarField> f23(F2());

    if (F3_)
    {
        f23.ref() *= F3();
    }

    return f23;
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
void
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
boundOmega()
{
    omega_ = max(omega_, k_/(this->nutMaxCoeff_*this->nu()));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
void
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
correctNut
(
    const volScalarField& S2,
    const volScalarField& F2,
    const volScalarField& F1
)
{
    this->nut_ = a1_*k_/max(a1_*omega_/alphaStar(F1), F2*sqrt(S2));
    this->nut_.correctBoundaryConditions();
    fvConstraints::New(this->mesh_).constrain(this->nut_);
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
void
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
correctNut()
{
    volScalarField CDkOmega
    (
        2*alphaOmega2_*(fvc::grad(k_) & fvc::grad(omega_))/omega_
    );

    correctNut(2*magSqr(symm(fvc::grad(this->U_))), F23(), F1(CDkOmega));
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField::Internal>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
Pk
(
    const volScalarField::Internal& G,
    const volScalarField::Internal& F1
) const
{
    return min(G, (c1_*betaStar(F1))*this->k_()*this->omega_());
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField::Internal>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
epsilonByk
(
    const volScalarField::Internal& F1,
    const volScalarField::Internal& F2
) const
{
    return betaStar(F1)*omega_();
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<fvScalarMatrix>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
kSource() const
{
    return tmp<fvScalarMatrix>
    (
        new fvScalarMatrix
        (
            k_,
            dimVolume*this->rho_.dimensions()*k_.dimensions()/dimTime
        )
    );
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<fvScalarMatrix>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
omegaSource() const
{
    return tmp<fvScalarMatrix>
    (
        new fvScalarMatrix
        (
            omega_,
            dimVolume*this->rho_.dimensions()*omega_.dimensions()/dimTime
        )
    );
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<fvScalarMatrix>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
Qsas
(
    const volScalarField::Internal& S2,
    const volScalarField::Internal& gamma,
    const volScalarField::Internal& beta
) const
{
    return tmp<fvScalarMatrix>
    (
        new fvScalarMatrix
        (
            omega_,
            dimVolume*this->rho_.dimensions()*omega_.dimensions()/dimTime
        )
    );
}


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

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

    alphaK1_("alphaK1", this->coeffDict(), 0.85),
    alphaK2_("alphaK2", this->coeffDict(), 1.0),
    alphaOmega1_("alphaOmega1", this->coeffDict(), 0.5),
    alphaOmega2_("alphaOmega2", this->coeffDict(), 0.856),
    alpha0_("alpha0", this->coeffDict(), 0.1 ),
    alphaStar0_("alphaStar0", this->coeffDict(), 0.025),
    alpha2_("alpha2", this->coeffDict(), 0.4404),
    beta1_("beta1", this->coeffDict(), 0.075),
    beta2_("beta2", this->coeffDict(), 0.0828),
    betaStar2_("betaStar2", this->coeffDict(), 0.09),
    alphaStar2_("alphaStar2", this->coeffDict(), 1.0),
    RBeta_("RBeta", this->coeffDict(), 8.0),
    RK_("RK", this->coeffDict(), 6.0),
    ROmega_("ROmega", this->coeffDict(), 2.7),
    a1_("a1", this->coeffDict(), 0.31),
    b1_("b1", this->coeffDict(), 1.0),
    c1_("c1", this->coeffDict(), 10.0),
    F3_(this->coeffDict().template lookupOrDefault<Switch>("F3", false)),

    y_(wallDist::New(this->mesh_).y()),

    k_
    (
        IOobject
        (
            this->groupName("k"),
            this->runTime_.name(),
            this->mesh_,
            IOobject::MUST_READ,
            IOobject::AUTO_WRITE
        ),
        this->mesh_
    ),
    omega_
    (
        IOobject
        (
            this->groupName("omega"),
            this->runTime_.name(),
            this->mesh_,
            IOobject::MUST_READ,
            IOobject::AUTO_WRITE
        ),
        this->mesh_
    )
{
    bound(k_, this->kMin_);
    boundOmega();
}


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

template<class MomentumTransportModel, class BasicMomentumTransportModel>
bool
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
read()
{
    if (MomentumTransportModel::read())
    {
        alphaK1_.readIfPresent(this->coeffDict());
        alphaK2_.readIfPresent(this->coeffDict());
        alphaOmega1_.readIfPresent(this->coeffDict());
        alphaOmega2_.readIfPresent(this->coeffDict());
        alpha0_.readIfPresent(this->coeffDict());
        alpha2_.readIfPresent(this->coeffDict());
        alphaStar0_.readIfPresent(this->coeffDict());
        beta1_.readIfPresent(this->coeffDict());
        beta2_.readIfPresent(this->coeffDict());
        betaStar2_.readIfPresent(this->coeffDict());
        alphaStar2_.readIfPresent(this->coeffDict());
        RBeta_.readIfPresent(this->coeffDict());
        RK_.readIfPresent(this->coeffDict());
        ROmega_.readIfPresent(this->coeffDict());
        a1_.readIfPresent(this->coeffDict());
        b1_.readIfPresent(this->coeffDict());
        c1_.readIfPresent(this->coeffDict());
        F3_.readIfPresent("F3", this->coeffDict());

        return true;
    }
    else
    {
        return false;
    }
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
tmp<volScalarField>
kOmegaSSTLangtrySjolander<MomentumTransportModel, BasicMomentumTransportModel>::
epsilon() const
{
    tmp<volScalarField> tEpsilon
    (
        volScalarField::New
        (
            "epsilon",
            this->mesh_,
            dimensionedScalar(dimensionSet(0, 2, -3, 0, 0), Zero)
        )
    );

    volScalarField& epsilon = tEpsilon.ref();

    volScalarField CDkOmega
    (
        (2*alphaOmega2_)*(fvc::grad(k_) & fvc::grad(omega_))/omega_
    );

    volScalarField F1(this->F1(CDkOmega));
    epsilon.internalFieldRef() = this->betaStar(F1)*k_*omega_;

    return tEpsilon;
}


template<class MomentumTransportModel, class BasicMomentumTransportModel>
void
kOmegaSSTLangtrySjolander<MomentumTransportModel, 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_;
    volScalarField& nut = this->nut_;
    const Foam::fvModels& fvModels(Foam::fvModels::New(this->mesh_));
    const Foam::fvConstraints& fvConstraints
    (
        Foam::fvConstraints::New(this->mesh_)
    );

    MomentumTransportModel::correct();

    volScalarField::Internal divU
    (
        fvc::div(fvc::absolute(this->phi(), U))()()
    );

    tmp<volTensorField> tgradU = fvc::grad(U);
    volScalarField S2(2*magSqr(symm(tgradU())));
    volScalarField::Internal GbyNu(dev(twoSymm(tgradU()())) && tgradU()());
    volScalarField::Internal G(this->GName(), nut()*GbyNu);
    tgradU.clear();

    // Update omega and G at the wall
    omega_.boundaryFieldRef().updateCoeffs();

    volScalarField CDkOmega
    (
        (2*alphaOmega2_)*(fvc::grad(k_) & fvc::grad(omega_))/omega_
    );

    volScalarField F1(this->F1(CDkOmega));
    volScalarField F23(this->F23());

    {
        volScalarField::Internal gamma(this->gamma(F1));
        volScalarField::Internal beta(this->beta(F1));
        volScalarField::Internal betaStar(this->betaStar(F1));

        // Turbulent frequency equation
        tmp<fvScalarMatrix> omegaEqn
        (
            fvm::ddt(alpha, rho, omega_)
          + fvm::div(alphaRhoPhi, omega_)
          - fvm::laplacian(alpha*rho*DomegaEff(F1), omega_)
         ==
            alpha()*rho()*gamma
           *min
            (
                GbyNu,
                (c1_/a1_)*betaStar*omega_()
               *max(a1_*omega_(), b1_*F23()*sqrt(S2()))
            )
          - fvm::SuSp((2.0/3.0)*alpha()*rho()*gamma*divU, omega_)
          - fvm::Sp(alpha()*rho()*beta*omega_(), omega_)
          - fvm::SuSp
            (
                alpha()*rho()*(F1() - scalar(1))*CDkOmega()/omega_(),
                omega_
            )
          + Qsas(S2(), gamma, beta)
          + omegaSource()
          + fvModels.source(alpha, rho, omega_)
        );

        omegaEqn.ref().relax();
        fvConstraints.constrain(omegaEqn.ref());
        omegaEqn.ref().boundaryManipulate(omega_.boundaryFieldRef());
        solve(omegaEqn);
        fvConstraints.constrain(omega_);
        boundOmega();
    }

    // Turbulent kinetic energy equation
    tmp<fvScalarMatrix> kEqn
    (
        fvm::ddt(alpha, rho, k_)
      + fvm::div(alphaRhoPhi, k_)
      - fvm::laplacian(alpha*rho*DkEff(F1), k_)
     ==
        alpha()*rho()*Pk(G, F1)
      - fvm::SuSp((2.0/3.0)*alpha()*rho()*divU, k_)
      - fvm::Sp(alpha()*rho()*epsilonByk(F1, F23), k_)
      + kSource()
      + fvModels.source(alpha, rho, k_)
    );

    kEqn.ref().relax();
    fvConstraints.constrain(kEqn.ref());
    solve(kEqn);
    fvConstraints.constrain(k_);
    bound(k_, this->kMin_);
    boundOmega();

    correctNut(S2, F23, F1);
}


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

} // End namespace Foam

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