/************************************************************************
 * MechSys tutorial: dry granular column collapse with several MPM
 * constitutive models.
 *
 * Build (outside the source tree):
 *   /home/sergio/mechsys/mechsyscc column.cpp -o column
 *
 * Run:
 *   ./column MODEL OUTKEY [Tf] [Nproc]
 *
 * MODEL: 1=Drucker-Prager, 2=Bui Drucker-Prager, 3=Hypoplastic, 5=mu(I)
 * OUTKEY: prefix written by MPM::Domain::Solve (OUTKEY_0000.h5, ...)
 ************************************************************************/

#include <mechsys/mpm/Domain.h>
#include <algorithm>
#include <cmath>
#include <iostream>

struct UserData
{
    double gravity;
};

static void SetGravity(MPM::Domain & dom, double gy)
{
    #pragma omp parallel for schedule(static) num_threads(dom.Nproc)
    for (size_t ip=0; ip<dom.Particles.Size(); ++ip)
    {
        MPM::Particle * p = dom.Particles[ip];
        p->b(0) = 0.0;
        p->b(1) = p->m*gy;
        p->b(2) = 0.0;
    }
}

static void Setup(MPM::Domain & dom, void * UD)
{
    UserData * dat = static_cast<UserData *>(UD);
    SetGravity(dom,dat->gravity);
}

static void Report(MPM::Domain & dom, void * UD)
{
    (void)UD;
    if (dom.idx_out % 10 != 0) return;
    double vmax = 0.0;
    double syy_min = 1.0e100;
    double syy_max = -1.0e100;
    for (size_t ip=0; ip<dom.Particles.Size(); ++ip)
    {
        MPM::Particle * p = dom.Particles[ip];
        vmax = std::max(vmax,norm(p->v));
        syy_min = std::min(syy_min,p->S(1,1));
        syy_max = std::max(syy_max,p->S(1,1));
    }
    std::cout << "Time: " << dom.Time
              << ", particles: " << dom.Particles.Size()
              << ", vmax: " << vmax
              << ", Syy: [" << syy_min << ", " << syy_max << "]" << std::endl;
}

static const char * ModelName(int model)
{
    switch (model)
    {
        case 0: return "Elastic (no yield)";
        case 1: return "Drucker-Prager (non-associated)";
        case 2: return "Bui Drucker-Prager (associated)";
        case 3: return "Hypoplastic";
        case 5: return "mu(I)";
        default: return "unsupported";
    }
}

int main(int argc, char ** argv) try
{
    if (argc < 3)
    {
        std::cerr << "usage: " << argv[0] << " MODEL OUTKEY [Tf] [Nproc]\n"
                  << "  MODEL: 0=Elastic, 1=DP, 2=Bui DP, 3=Hypoplastic, 5=mu(I)\n";
        return 2;
    }

    const int    model = atoi(argv[1]);
    const char * key   = argv[2];
    const double Tf    = (argc>3) ? atof(argv[3]) : 1.20;
    size_t       Nproc = (argc>4) ? atoi(argv[4]) : 32;

    if (model!=0 && model!=1 && model!=2 && model!=3 && model!=5)
    {
        std::cerr << "unsupported model " << model << std::endl;
        return 2;
    }

    // Column geometry: width Lx, height Ly, shallow depth Lz.  The shallow
    // depth keeps the CPU tutorial small; the side view is the x-y plane.
    const double Lx = 0.10;
    const double Ly = 0.10;
    const double Lz = 0.04;
    const size_t ndiv = 20;              // material points across Lx
    const double h = Lx/ndiv;           // material-point spacing
    const double Dx = 2.0*h;            // MPM grid spacing (8 points/cell)
    const double rho = 1800.0;
    const double gravity = 9.81;

    MPM::Domain dom;
    UserData dat;
    dat.gravity = -gravity;
    dom.UserData = &dat;
    dom.ShapeFunction = MPM::SHAPE_BSPLINE_QUADRATIC;

    dom.AddRectangularBeam(-1, Vec3_t(0.0,0.0,0.0), Vec3_t(Lx,Ly,Lz), rho, ndiv);

    // Enough free board for the runout, with two ghost cells around it.
    const double xmin = -0.10;
    const double xmax =  0.34;
    const double ymin = -0.02;
    const double ymax =  0.18;
    const double zmin = -0.08;
    const double zmax =  0.14;
    dom.ResizeDomain(Vec3_t(xmin,ymin,zmin),Vec3_t(xmax,ymax,zmax),Dx);

    // Fixed ground at y=0.
    for (size_t in=0; in<dom.Nnodes; ++in)
    {
        Vec3_t xn;
        dom.NodePosition(in,xn);
        if (xn(1) <= 0.5*Dx) dom.Nodes[in].FixVeloc();
    }

    // Constitutive parameters.  These are tutorial values, not a calibrated
    // parameter set for a particular sand.
    const double E   = 1.0e7;
    const double nu  = 0.30;
    const double K   = E/(3.0*(1.0-2.0*nu));
    const double G   = E/(2.0*(1.0+nu));
    const double phi = 30.0*M_PI/180.0;
    const double psi =  0.0*M_PI/180.0;

    const double mui_K    = 2.6e4;   // Pa
    const double mui_rhos = 2000.0;  // grain density
    const double phi_s    = 0.65;
    const double mui_rho  = phi_s*mui_rhos;
    const double mui_cs   = std::sqrt(mui_K/mui_rho);
    const double mui_mus  = 0.3819;
    const double mui_mu2  = 0.5718;
    const double mui_I0   = 0.279;
    const double mui_d    = 0.0053;
    const double mui_reg  = 1.0e-4;

    for (size_t ip=0; ip<dom.Particles.Size(); ++ip)
    {
        MPM::Particle * p = dom.Particles[ip];
        p->Constitutive = model;
        p->Cohesion = 0.0;
        if (model==0 || model==1 || model==2)
        {
            p->K = K;
            p->G = G;
            p->Friction = phi;
            if (model==2)
            {
                // Bui's associated variant: plastic potential = yield surface.
                p->Dilation = phi;
                p->Fail = 2;
            }
            else
            {
                // Drucker-Prager with a non-associated, zero-dilation flow rule.
                p->Dilation = psi;
                p->Fail = 3;
            }
        }
        else if (model==3)
        {
            // Guo et al. (2016) default dimensionless constants for dry
            // polystyrene beads, as initialised by MPM::Particle.
            p->Cohesion = 0.0;
        }
        else if (model==5)
        {
            p->K = mui_K;
            p->Cs = mui_cs;
            p->EOSType = MPM::EOS_LINEAR;
            p->EOSexp = 1.0;
            p->MuIStatic = mui_mus;
            p->MuIDynamic = mui_mu2;
            p->MuII0 = mui_I0;
            p->GrainDiameter = mui_d;
            p->GrainRho = mui_rhos;
            p->MuIReg = mui_reg;
        }
    }

    const double vscale = std::sqrt(2.0*gravity*Ly);
    double dt = 0.0;
    double signal = 0.0;
    if (model==0 || model==1 || model==2)
    {
        signal = std::sqrt((K + 4.0*G/3.0)/rho);
        dt = 0.1*h/signal;
    }
    else if (model==3)
    {
        signal = 100.0*vscale;
        dt = 0.1*std::min(h/(10.0*vscale),std::min(h/signal,std::sqrt(h/gravity)));
    }
    else
    {
        signal = mui_cs;
        dt = 0.05*Dx/(mui_cs + vscale);
    }

    dom.Gn = 0.001; // small background damping
    const double dtOut = Tf/99.0;

    std::cout << "Model: " << ModelName(model) << " (" << model << ")\n"
              << "Particles: " << dom.Particles.Size() << "\n"
              << "Grid spacing: " << Dx << " m\n"
              << "Signal speed: " << signal << " m/s\n"
              << "Time step: " << dt << " s\n"
              << "Output interval: " << dtOut << " s\n"
              << "Final time: " << Tf << " s\n" << std::flush;

    dom.Solve(Tf,dt,dtOut,Setup,Report,key,true,Nproc);
    return 0;
}
MECHSYS_CATCH
