#----------------------------------------------------------------------
#  Spectral GFDM method test - 2d beam structural analysis
#  Author: Andrea Pavan
#  Date: 01/03/2023
#  License: GPLv3-or-later
#----------------------------------------------------------------------
using ElasticArrays;
using LinearAlgebra;
using SparseArrays;
using PyPlot;
include("utils.jl");


#problem definition
l1 = 20.0;      #domain x size
l2 = 1.0;       #domain y size
E = 71.7e9;     #Young modulus
ν = 0.33;       #Poisson ratio
qy = 1e5;       #distributed load on the top

meshSize = 0.2;
#meshSize = 0.125;
surfaceMeshSize = meshSize;
minNeighbors = 10;
minSearchRadius = meshSize;


#pointcloud generation
time1 = time();
pointcloud = ElasticArray{Float64}(undef,2,0);      #2xN matrix containing the coordinates [X;Y] of each node
boundaryNodes = Vector{Int};        #indices of the boundary nodes
normals = ElasticArray{Float64}(undef,2,0);     #2xN matrix containing the components [nx;ny] of the normal of each boundary node
for i=0+surfaceMeshSize:surfaceMeshSize:l2-surfaceMeshSize
    append!(pointcloud, [0,i]);
    append!(normals, [-1,0]);
    append!(pointcloud, [l1,i]);
    append!(normals, [1,0]);
end
for i=0+surfaceMeshSize:surfaceMeshSize:l1-surfaceMeshSize
#for i=0:surfaceMeshSize:l1
    append!(pointcloud, [i,0]);
    append!(normals, [0,-1]);
    append!(pointcloud, [i,l2]);
    append!(normals, [0,1]);
end
boundaryNodes = collect(range(1,size(pointcloud,2)));
for x=0+meshSize:meshSize:l1-meshSize
    for y=0+meshSize:meshSize:l2-meshSize
        newP = [x,y]+(rand(Float64,2).-0.5).*meshSize/5;
        insertP = true;
        for j in boundaryNodes
            if (newP[1]-pointcloud[1,j])^2+(newP[2]-pointcloud[2,j])^2<(0.75*meshSize)^2
                insertP = false;
            end
        end
        if insertP
            append!(pointcloud, newP);
            append!(normals, [0,0]);
        end
    end
end
internalNodes = collect(range(1+length(boundaryNodes),size(pointcloud,2)));
println("Generated pointcloud in ", round(time()-time1,digits=2), " s");
println("Pointcloud properties:");
println("  Boundary nodes: ",length(boundaryNodes));
println("  Internal nodes: ",length(internalNodes));
println("  Memory: ",memoryUsage(pointcloud,boundaryNodes));

#pointcloud plot
#=figure();
plot(pointcloud[1,boundaryNodes],pointcloud[2,boundaryNodes],"r.");
plot(pointcloud[1,internalNodes],pointcloud[2,internalNodes],"k.");
title("Pointcloud plot");
axis("equal");
display(gcf());=#


#neighbor search
time2 = time();
N = size(pointcloud,2);     #number of nodes
neighbors = Vector{Vector{Int}}(undef,N);       #vector containing N vectors of the indices of each node neighbors
Nneighbors = zeros(Int,N);      #number of neighbors of each node
for i=1:N
    searchradius = minSearchRadius;
    while Nneighbors[i]<minNeighbors
        neighbors[i] = Int[];
        #check every other node
        for j=1:N
            if j!=i && all(abs.(pointcloud[:,j]-pointcloud[:,i]).<searchradius)
                push!(neighbors[i],j);
            end
        end
        unique!(neighbors[i]);
        Nneighbors[i] = length(neighbors[i]);
        searchradius += minSearchRadius/2;
    end
end
boundaryNeighbors  = Vector{Vector{Int}}(undef,N);       #vector containing N vectors of the indices of each node boundary neighbors
NboundaryNeighbors = zeros(Int,N);      #number of boundary neighbors of each node
for i=1:N
    boundaryNeighbors[i] = Int[];
    for j=1:Nneighbors[i]
        if sum(abs.(normals[:,neighbors[i][j]]))>0.1
            push!(boundaryNeighbors[i], neighbors[i][j]);
        end
    end
    NboundaryNeighbors[i] = length(boundaryNeighbors[i]);
end
println("Found neighbors in ", round(time()-time2,digits=2), " s");
println("Connectivity properties:");
println("  Max neighbors: ",maximum(Nneighbors)," (at index ",findfirst(isequal(maximum(Nneighbors)),Nneighbors),")");
println("  Avg neighbors: ",round(sum(Nneighbors)/length(Nneighbors),digits=2));
println("  Min neighbors: ",minimum(Nneighbors)," (at index ",findfirst(isequal(minimum(Nneighbors)),Nneighbors),")");


#neighbors distances and weights
time3 = time();
P = Vector{Array{Float64}}(undef,N);        #relative positions of the neighbors
r2 = Vector{Vector{Float64}}(undef,N);      #relative distances of the neighbors
w = Vector{Vector{Float64}}(undef,N);       #neighbors weights
for i=1:N
    P[i] = Array{Float64}(undef,2,Nneighbors[i]);
    r2[i] = Vector{Float64}(undef,Nneighbors[i]);
    w[i] = Vector{Float64}(undef,Nneighbors[i]);
    for j=1:Nneighbors[i]
        P[i][:,j] = pointcloud[:,neighbors[i][j]]-pointcloud[:,i];
        r2[i][j] = P[i][:,j]'P[i][:,j];
    end
    r2max = maximum(r2[i]);
    for j=1:Nneighbors[i]
        w[i][j] = exp(-6*r2[i][j]/r2max);
        #w[i][j] = 1.0;
    end
end
wpde = 2.0;       #least squares weight for the pde
wbc = 2.0;        #least squares weight for the boundary condition


#boundary conditions
N = size(pointcloud,2);     #number of nodes
Nb = length(boundaryNodes);     #number of boundary nodes
g1u = zeros(Float64,N);
g2u = zeros(Float64,N);
g3u = zeros(Float64,N);
g1v = zeros(Float64,N);
g2v = zeros(Float64,N);
g3v = zeros(Float64,N);
for i in boundaryNodes
    if pointcloud[1,i]<=0+1e-6
        #left side - u=0, v=0
        g1u[i] = 1.0;
        g2u[i] = 0.0;
        g3u[i] = 0.0;
        g1v[i] = 1.0;
        g2v[i] = 0.0;
        g3v[i] = 0.0;
    elseif pointcloud[2,i]>=l2-1e-6
        #top side - qy=-1e5
        g1u[i] = 0.0;
        g2u[i] = 1.0;
        g3u[i] = 0.0;
        g1v[i] = 0.0;
        g2v[i] = 1.0;
        g3v[i] = qy;
    else
        #everywhere else
        g1u[i] = 0.0;
        g2u[i] = 1.0;
        g3u[i] = 0.0;
        g1v[i] = 0.0;
        g2v[i] = 1.0;
        g3v[i] = 0.0;
    end
end
Fx = zeros(Float64,N);      #volumetric loads
Fy = zeros(Float64,N);


#stencil coefficients - Spectral GFDM
C = Vector{Matrix}(undef,N);        #stencil coefficients matrices
condC = zeros(N);       #stencil condition number
for i=1:N
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,Nneighbors[i]+NboundaryNeighbors[i],6);
    for j=1:Nneighbors[i]
        V[j,:] = [1, xj[j], yj[j], xj[j]^2, yj[j]^2, xj[j]*yj[j]];
    end
    for j=1:NboundaryNeighbors[i]
        nx = normals[1,boundaryNeighbors[i][j]];
        ny = normals[2,boundaryNeighbors[i][j]];
        xc = pointcloud[1,boundaryNeighbors[i][j]]-pointcloud[1,i];
        yc = pointcloud[2,boundaryNeighbors[i][j]]-pointcloud[2,i];
        V[j+Nneighbors[i],:] = [0, nx, ny, 2*xc*nx, 2*yc*ny, nx*yc+ny*xc];
    end
    W = Diagonal(vcat(w[i],ones(NboundaryNeighbors[i])));
    VF = svd(W*V);
    C[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
    condC[i] = cond(C[i]);
end
println("Inverted least-squares matrices in ", round(time()-time3,digits=2), " s");
println("Stencil properties:");
println("  Max cond(C): ", trunc(Int,maximum(condC)));
println("  Avg cond(C): ", trunc(Int,sum(condC)/N));
println("  Min cond(C): ", trunc(Int,minimum(condC)));


#matrix assembly
time4 = time();
rows = Int[];
cols = Int[];
vals = Float64[];
for i=1:N
    #u equation
    for j=1:Nneighbors[i]
        push!(rows, i);
        push!(cols, neighbors[i][j]);
        push!(vals, 2*(1/(1-ν^2))*C[i][4,j] + 2*(0.5*1/(1+ν))*C[i][5,j]);
        push!(rows, i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, (1*ν/(1-ν^2))*C[i][6,j] + (0.5*1/(1+ν))*C[i][6,j]);
    end
    for j=1:NboundaryNeighbors[i]
        push!(rows, i);
        push!(cols, 2*N+boundaryNeighbors[i][j]);
        push!(vals, 2*(1/(1-ν^2))*C[i][4,j+Nneighbors[i]] + 2*(0.5*1/(1+ν))*C[i][5,j+Nneighbors[i]]);
        push!(rows, i);
        push!(cols, 2*N+Nb+boundaryNeighbors[i][j]);
        push!(vals, (1*ν/(1-ν^2))*C[i][6,j+Nneighbors[i]] + (0.5*1/(1+ν))*C[i][6,j+Nneighbors[i]]);
    end

    #v equation
    for j=1:Nneighbors[i]
        push!(rows, N+i);
        push!(cols, neighbors[i][j]);
        push!(vals, (1*ν/(1-ν^2))*C[i][6,j] + (0.5*1/(1+ν))*C[i][6,j]);
        push!(rows, N+i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, 2*(1/(1-ν^2))*C[i][5,j] + 2*(0.5*1/(1+ν))*C[i][4,j]);
    end
    for j=1:NboundaryNeighbors[i]
        push!(rows, N+i);
        push!(cols, 2*N+boundaryNeighbors[i][j]);
        push!(vals, (1*ν/(1-ν^2))*C[i][6,j+Nneighbors[i]] + (0.5*1/(1+ν))*C[i][6,j+Nneighbors[i]]);
        push!(rows, N+i);
        push!(cols, 2*N+Nb+boundaryNeighbors[i][j]);
        push!(vals, 2*(1/(1-ν^2))*C[i][5,j+Nneighbors[i]] + 2*(0.5*1/(1+ν))*C[i][4,j+Nneighbors[i]]);
    end
end
for i in boundaryNodes
    nx = normals[1,i];
    ny = normals[2,i];

    #u boundary condition
    push!(rows, 2*N+i);
    push!(cols, i);
    push!(vals, g1u[i]/E);
    for j=1:Nneighbors[i]
        push!(rows, 2*N+i);
        push!(cols, neighbors[i][j]);
        push!(vals, g2u[i]*nx*(1/(1-ν^2))*C[i][2,j] + g2u[i]*ny*(0.5*1/(1+ν))*C[i][3,j]);
        push!(rows, 2*N+i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, g2u[i]*nx*(1*ν/(1-ν^2))*C[i][3,j] + g2u[i]*ny*(0.5*1/(1+ν))*C[i][2,j]);
    end
    for j=1:NboundaryNeighbors[i]
        push!(rows, 2*N+i);
        push!(cols, 2*N+boundaryNeighbors[i][j]);
        push!(vals, g2u[i]*nx*(1/(1-ν^2))*C[i][2,j+Nneighbors[i]] + g2u[i]*ny*(0.5*1/(1+ν))*C[i][3,j+Nneighbors[i]]);
        push!(rows, 2*N+i);
        push!(cols, 2*N+Nb+boundaryNeighbors[i][j]);
        push!(vals, g2u[i]*nx*(1*ν/(1-ν^2))*C[i][3,j+Nneighbors[i]] + g2u[i]*ny*(0.5*1/(1+ν))*C[i][2,j+Nneighbors[i]]);
    end
    
    #v boundary condition
    push!(rows, 2*N+Nb+i);
    push!(cols, N+i);
    push!(vals, g1v[i]/E);
    for j=1:Nneighbors[i]
        push!(rows, 2*N+Nb+i);
        push!(cols, neighbors[i][j]);
        push!(vals, g2v[i]*nx*(0.5*1/(1+ν))*C[i][3,j] + g2v[i]*ny*(1*ν/(1-ν^2))*C[i][2,j]);
        push!(rows, 2*N+Nb+i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, g2v[i]*nx*(0.5*1/(1+ν))*C[i][2,j] + g2v[i]*ny*(1/(1-ν^2))*C[i][3,j]);
    end
    for j=1:NboundaryNeighbors[i]
        push!(rows, 2*N+Nb+i);
        push!(cols, 2*N+boundaryNeighbors[i][j]);
        push!(vals, g2v[i]*nx*(0.5*1/(1+ν))*C[i][3,j+Nneighbors[i]] + g2v[i]*ny*(1*ν/(1-ν^2))*C[i][2,j+Nneighbors[i]]);
        push!(rows, 2*N+Nb+i);
        push!(cols, 2*N+Nb+boundaryNeighbors[i][j]);
        push!(vals, g2v[i]*nx*(0.5*1/(1+ν))*C[i][2,j+Nneighbors[i]] + g2v[i]*ny*(1/(1-ν^2))*C[i][3,j+Nneighbors[i]]);
    end
end
M = sparse(rows,cols,vals,2*N+2*Nb,2*N+2*Nb);
println("Completed matrix assembly in ", round(time()-time4,digits=2), " s");


#linear system solution
time5 = time();
b = zeros(2*N+2*Nb);        #rhs vector
for i=1:N
    b[i] = -Fx[i]/E;
    b[N+i] = -Fy[i]/E;
end
for i in boundaryNodes
    b[2*N+i] = g3u[i]/E;
    b[2*N+Nb+i] = g3v[i]/E;
end
sol = qr(M)\b;
#using IterativeSolvers;
#using Preconditioners;
#PM = DiagonalPreconditioner(M);
#sol = idrs(M,b,Pl=PM,verbose=true);
#sol = bicgstabl(M,b,Pl=PM,verbose=true);
#sol = gmres(M,b,Pl=PM,verbose=true);
println("Linear system solved in ", round(time()-time5,digits=2), " s");


#solution plot
u = sol[1:N];
v = sol[N+1:2*N];
figure();
scatter(pointcloud[1,:],pointcloud[2,:],c=u,cmap="jet");
colorbar();
title("Numerical solution - x displacement");
axis("equal");
display(gcf());
figure();
scatter(pointcloud[1,:],pointcloud[2,:],c=v,cmap="jet");
colorbar();
title("Numerical solution - y displacement");
axis("equal");
display(gcf());

#deformed beam plot
figure();
scatter(pointcloud[1,:]+u/maximum(abs.(v)),pointcloud[2,:]+v/maximum(abs.(v)),c=v,cmap="Oranges");
colorbar();
title("Numerical solution - deflection");
axis("equal");
display(gcf());

println("\nEuler-Bernoulli beam theory:");
println("> vmax = ",qy*(l1^4)/(8*E*(l2^4)/12));
println("GFDM:");
println("> umax = ",maximum(abs.(u)));
println("> vmax = ",maximum(abs.(v)));
