/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 1991-2010 OpenCFD Ltd.
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM 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.

    OpenFOAM 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 OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

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

#include "leastSquaresVectors.H"
#include <finiteVolume/surfaceFields.H>
#include <finiteVolume/volFields.H>

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
    defineTypeNameAndDebug(leastSquaresVectors, 0);
}


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

Foam::leastSquaresVectors::leastSquaresVectors(const fvMesh& mesh)
:
    MeshObject<fvMesh, leastSquaresVectors>(mesh),
    pVectorsPtr_(NULL),
    nVectorsPtr_(NULL)
{}


// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //

Foam::leastSquaresVectors::~leastSquaresVectors()
{
    deleteDemandDrivenData(pVectorsPtr_);
    deleteDemandDrivenData(nVectorsPtr_);
}


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

void Foam::leastSquaresVectors::makeLeastSquaresVectors() const
{
    if (debug)
    {
        Info<< "leastSquaresVectors::makeLeastSquaresVectors() :"
            << "Constructing least square gradient vectors"
            << endl;
    }

    const fvMesh& mesh = mesh_;

    pVectorsPtr_ = new surfaceVectorField
    (
        IOobject
        (
            "LeastSquaresP",
            mesh_.pointsInstance(),
            mesh_,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        mesh_,
        dimensionedVector("zero", dimless/dimLength, vector::zero)
    );
    surfaceVectorField& lsP = *pVectorsPtr_;

    nVectorsPtr_ = new surfaceVectorField
    (
        IOobject
        (
            "LeastSquaresN",
            mesh_.pointsInstance(),
            mesh_,
            IOobject::NO_READ,
            IOobject::NO_WRITE,
            false
        ),
        mesh_,
        dimensionedVector("zero", dimless/dimLength, vector::zero)
    );
    surfaceVectorField& lsN = *nVectorsPtr_;

    // Set local references to mesh data
    const unallocLabelList& owner = mesh_.owner();
    const unallocLabelList& neighbour = mesh_.neighbour();

    const volVectorField& C = mesh.C();
    const surfaceScalarField& w = mesh.weights();
    const surfaceScalarField& magSf = mesh.magSf();


    // Set up temporary storage for the dd tensor (before inversion)
    symmTensorField dd(mesh_.nCells(), symmTensor::zero);

    forAll(owner, facei)
    {
        label own = owner[facei];
        label nei = neighbour[facei];

        vector d = C[nei] - C[own];
        symmTensor wdd = (magSf[facei]/magSqr(d))*sqr(d);

        dd[own] += (1 - w[facei])*wdd;
        dd[nei] += w[facei]*wdd;
    }


    forAll(lsP.boundaryField(), patchi)
    {
        const fvsPatchScalarField& pw = w.boundaryField()[patchi];
        const fvsPatchScalarField& pMagSf = magSf.boundaryField()[patchi];

        const fvPatch& p = pw.patch();
        const unallocLabelList& faceCells = p.patch().faceCells();

        // Build the d-vectors
        vectorField pd =
            mesh.Sf().boundaryField()[patchi]
           /(
               mesh.magSf().boundaryField()[patchi]
              *mesh.deltaCoeffs().boundaryField()[patchi]
           );

        if (!mesh.orthogonal())
        {
            pd -= mesh.correctionVectors().boundaryField()[patchi]
                /mesh.deltaCoeffs().boundaryField()[patchi];
        }

        if (p.coupled())
        {
            forAll(pd, patchFacei)
            {
                const vector& d = pd[patchFacei];

                dd[faceCells[patchFacei]] +=
                    ((1 - pw[patchFacei])*pMagSf[patchFacei]/magSqr(d))*sqr(d);
            }
        }
        else
        {
            forAll(pd, patchFacei)
            {
                const vector& d = pd[patchFacei];

                dd[faceCells[patchFacei]] +=
                    (pMagSf[patchFacei]/magSqr(d))*sqr(d);
            }
        }
    }


    // Invert the dd tensor
    symmTensorField invDd = inv(dd);


    // Revisit all faces and calculate the lsP and lsN vectors
    forAll(owner, facei)
    {
        label own = owner[facei];
        label nei = neighbour[facei];

        vector d = C[nei] - C[own];
        scalar magSfByMagSqrd = magSf[facei]/magSqr(d);

        lsP[facei] = (1 - w[facei])*magSfByMagSqrd*(invDd[own] & d);
        lsN[facei] = -w[facei]*magSfByMagSqrd*(invDd[nei] & d);
    }

    forAll(lsP.boundaryField(), patchi)
    {
        fvsPatchVectorField& patchLsP = lsP.boundaryField()[patchi];

        const fvsPatchScalarField& pw = w.boundaryField()[patchi];
        const fvsPatchScalarField& pMagSf = magSf.boundaryField()[patchi];

        const fvPatch& p = pw.patch();
        const unallocLabelList& faceCells = p.faceCells();

        // Build the d-vectors
        vectorField pd =
            mesh.Sf().boundaryField()[patchi]
           /(
               mesh.magSf().boundaryField()[patchi]
              *mesh.deltaCoeffs().boundaryField()[patchi]
           );

        if (!mesh.orthogonal())
        {
            pd -= mesh.correctionVectors().boundaryField()[patchi]
                /mesh.deltaCoeffs().boundaryField()[patchi];
        }


        if (p.coupled())
        {
            forAll(pd, patchFacei)
            {
                const vector& d = pd[patchFacei];

                patchLsP[patchFacei] =
                    ((1 - pw[patchFacei])*pMagSf[patchFacei]/magSqr(d))
                   *(invDd[faceCells[patchFacei]] & d);
            }
        }
        else
        {
            forAll(pd, patchFacei)
            {
                const vector& d = pd[patchFacei];

                patchLsP[patchFacei] =
                    pMagSf[patchFacei]*(1.0/magSqr(d))
                   *(invDd[faceCells[patchFacei]] & d);
            }
        }
    }


    // For 3D meshes check the determinant of the dd tensor and switch to
    // Gauss if it is less than 3
    /* Currently the det(dd[celli]) criterion is incorrect: dd is weighted by Sf
    if (mesh.nGeometricD() == 3)
    {
        label nBadCells = 0;

        const cellList& cells = mesh.cells();
        const scalarField& V = mesh.V();
        const surfaceVectorField& Sf = mesh.Sf();
        const surfaceScalarField& w = mesh.weights();

        forAll (dd, celli)
        {
            if (det(dd[celli]) < 3)
            {
                nBadCells++;

                const cell& c = cells[celli];

                forAll(c, cellFacei)
                {
                    label facei = c[cellFacei];

                    if (mesh.isInternalFace(facei))
                    {
                        scalar wf = max(min(w[facei], 0.8), 0.2);

                        if (celli == owner[facei])
                        {
                            lsP[facei] = (1 - wf)*Sf[facei]/V[celli];
                        }
                        else
                        {
                            lsN[facei] = -wf*Sf[facei]/V[celli];
                        }
                    }
                    else
                    {
                        label patchi = mesh.boundaryMesh().whichPatch(facei);

                        if (mesh.boundary()[patchi].size())
                        {
                            label patchFacei =
                                facei - mesh.boundaryMesh()[patchi].start();

                            if (mesh.boundary()[patchi].coupled())
                            {
                                scalar wf = max
                                (
                                    min
                                    (
                                        w.boundaryField()[patchi][patchFacei],
                                        0.8
                                    ),
                                    0.2
                                );

                                lsP.boundaryField()[patchi][patchFacei] =
                                    (1 - wf)
                                   *Sf.boundaryField()[patchi][patchFacei]
                                   /V[celli];
                            }
                            else
                            {
                                lsP.boundaryField()[patchi][patchFacei] =
                                    Sf.boundaryField()[patchi][patchFacei]
                                   /V[celli];
                            }
                        }
                    }
                }
            }
        }

        if (debug)
        {
            InfoIn("leastSquaresVectors::makeLeastSquaresVectors()")
                << "number of bad cells switched to Gauss = " << nBadCells
                << endl;
        }
    }
    */

    if (debug)
    {
        Info<< "leastSquaresVectors::makeLeastSquaresVectors() :"
            << "Finished constructing least square gradient vectors"
            << endl;
    }
}


const Foam::surfaceVectorField& Foam::leastSquaresVectors::pVectors() const
{
    if (!pVectorsPtr_)
    {
        makeLeastSquaresVectors();
    }

    return *pVectorsPtr_;
}


const Foam::surfaceVectorField& Foam::leastSquaresVectors::nVectors() const
{
    if (!nVectorsPtr_)
    {
        makeLeastSquaresVectors();
    }

    return *nVectorsPtr_;
}


bool Foam::leastSquaresVectors::movePoints()
{
    deleteDemandDrivenData(pVectorsPtr_);
    deleteDemandDrivenData(nVectorsPtr_);

    return true;
}


// ************************ vim: set sw=4 sts=4 et: ************************ //
