/*--------------------------------*- C++ -*----------------------------------*\
  ==  == ====== ====   ====    |
                    \\     ||  | Multiphase Cases Repository by HZDR
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.811
  ||  ||  //    ||  // || \\   | License: Creative Commons Attribution 4.0
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
Description
    Creates two common gas fields in aearated stirred tanks:
    - alphaHeadspace : continuous gas connected to headspace patches
    - alphaCavity  : continuous gas connected to cavity patches (pockets)

    Uses connectivity logic similar to regionSizeDistribution based on a
    threshold, and computes the total gas holdup within the liquid region.

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

libs                ("libutilityFunctionObjects.so");
type                coded;

name                gasHoldup;
gasPhases          (air);
threshold           0.5;
headspacePatches   (outlet);
cavityPatches      (stirrer);
log                 true;
writeFields         true;
executeControl      writeTime;
writeControl        writeTime;

codeInclude
#{
    #include "OFstream.H"
    #include "OSspecific.H"
    #include "volFields.H"
    #include "regionSplit.H"
#};

codeData
#{
    wordList    gasPhases_;
    scalar      threshold_;
    wordReList  headspacePatches_;
    wordReList  cavityPatches_;
    bool        log_;
    bool        writeFields_;

    autoPtr<volScalarField> alphaHeadspace_;
    autoPtr<volScalarField> alphaCavity_;
    scalar VHead_;
    scalar VCavity_;
    scalar totalGasHoldup_;
    scalar dispersedGasHoldup_;
    autoPtr<OFstream> file;
#};

codeRead
#{
    gasPhases_ = dict.lookup<wordList>("gasPhases");
    threshold_ = dict.lookup<scalar>("threshold");
    headspacePatches_ = dict.lookup<wordReList>("headspacePatches");
    cavityPatches_ = dict.lookup<wordReList>("cavityPatches");
    log_ = dict.lookupOrDefault<bool>("log", false);
    writeFields_ = dict.lookupOrDefault<bool>("writeFields", false);

    // Gas fraction in headspace
    alphaHeadspace_.set
    (
        new volScalarField
        (
            IOobject
            (
                "alphaHeadspace",
                mesh().time().name(),
                mesh(),
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            mesh(),
            dimensionedScalar("alphaHeadspace", dimless, Zero)
        )
    );

    // Gas fraction in cavities
    alphaCavity_.set
    (
        new volScalarField
        (
            IOobject
            (
                "alphaCavity",
                mesh().time().name(),
                mesh(),
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            mesh(),
            dimensionedScalar("alphaCavity", dimless, Zero)
        )
    );

    fileName dir
    (
        mesh().time().globalPath()/
        "postProcessing"/
        name()/
        mesh().time().name()
    );

    mkDir(dir);
    file = new OFstream(dir/$name + ".dat");

    file()<< "# Time" << tab << "gasVolumeHeadspace"
        << tab << "gasVolumeCavities"
        << tab << "totalGasHoldup"
        << tab << "dispersedGasHoldup" << endl;
#};

codeExecute
#{
    const scalar& threshold = threshold_;
    volScalarField alphaTotal
    (
        IOobject
        (
            "alphaTotal",
            mesh().time().name(),
            mesh(),
            IOobject::NO_READ,
            IOobject::NO_WRITE
        ),
        mesh(),
        dimensionedScalar("zero", dimless, 0.0)
    );

    forAll(gasPhases_, i)
    {
        const word& name = gasPhases_[i];

        const volScalarField& alpha =
            mesh().foundObject<volScalarField>("alphaMean." + name)
            ? mesh().lookupObject<volScalarField>("alphaMean." + name)
            : mesh().lookupObject<volScalarField>("alpha." + name);

        alphaTotal += alpha;
    }

    const wordReList& headspacePatches = headspacePatches_;
    const wordReList& cavityPatches = cavityPatches_;

    boolList blockedFace(mesh().nFaces(), false);

    for (label facei = 0; facei < mesh().nInternalFaces(); facei++)
    {
        scalar own = alphaTotal[mesh().faceOwner()[facei]];
        scalar nei = alphaTotal[mesh().faceNeighbour()[facei]];

        if ((own > threshold) != (nei > threshold))
        {
            blockedFace[facei] = true;
        }
    }

    regionSplit regions(mesh(), blockedFace);
    if (log_)
    {
        Info<< "    Found " << regions.nRegions()
            << " regions" << endl;
    }

    labelHashSet patchIDsH = mesh().poly().boundary().patchSet(headspacePatches);
    labelHashSet patchIDsC = mesh().poly().boundary().patchSet(cavityPatches);
    Map<bool> isHeadspaceRegion;
    Map<bool> isCavityRegion;

    forAllConstIter(labelHashSet, patchIDsH, iter)
    {
        const polyPatch& pp = mesh().poly().boundary()[iter.key()];
        const labelList& faceCells = pp.faceCells();

        forAll(faceCells, i)
        {
            label regionI = regions[faceCells[i]];
            isHeadspaceRegion.insert(regionI, true);
        }
    }

    forAllConstIter(labelHashSet, patchIDsC, iter)
    {
        const polyPatch& pp = mesh().poly().boundary()[iter.key()];
        const labelList& faceCells = pp.faceCells();

        forAll(faceCells, i)
        {
            label regionI = regions[faceCells[i]];
            isCavityRegion.insert(regionI, true);
        }
    }

    // Make sure all the processors have the same set of regions
    Pstream::mapCombineGather(isHeadspaceRegion, orEqOp<bool>());
    Pstream::mapCombineScatter(isHeadspaceRegion);
    Pstream::mapCombineGather(isCavityRegion, orEqOp<bool>());
    Pstream::mapCombineScatter(isCavityRegion);

    alphaHeadspace_() = 0.0;
    alphaCavity_() = 0.0;
    forAll(alphaTotal, celli)
    {
        if (alphaTotal[celli] > threshold)
        {
            label regionI = regions[celli];

            if (isHeadspaceRegion.found(regionI))
            {
                alphaHeadspace_()[celli] = alphaTotal[celli];
            }
            if (isCavityRegion.found(regionI))
            {
                alphaCavity_()[celli] = alphaTotal[celli];
            }
        }
    }

    const scalarField& V = mesh().V();
    VHead_ = gSum(alphaHeadspace_()*V);
    VCavity_ = gSum(alphaCavity_()*V);
    totalGasHoldup_ = (gSum(alphaTotal()*V) - VHead_)/(gSum(V) - VHead_);
    dispersedGasHoldup_ =
        (gSum(alphaTotal()*V) - VHead_ - VCavity_)
       /(gSum(V) - VHead_);

    if (log_)
    {
        Info<< "    Gas volume in headspace = " << VHead_ << nl;
        Info<< "    Gas volume in cavities = " << VCavity_ << nl;
        Info<< "    Total gas holdup = " << totalGasHoldup_ << nl;
        Info<< "    Dispersed gas holdup = " << dispersedGasHoldup_ << nl;
    }
#};

codeWrite
#{
    if (writeFields_)
    {
        alphaHeadspace_->write();
        alphaCavity_->write();
    }

    file()<< mesh().time().userTimeValue() << tab << VHead_
        << tab << VCavity_
        << tab << totalGasHoldup_
        << tab << dispersedGasHoldup_ << endl;
#};

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