#----------------------------------------------------------------------
#  GFDM method test - 2d elastic plate with a hole
#  Author: Andrea Pavan
#  Date: 14/02/2023
#  License: GPLv3-or-later
#----------------------------------------------------------------------
using ElasticArrays;
using LinearAlgebra;
using SparseArrays;
using PyPlot;
include("utils.jl");


#problem definition
l1 = 10.0;      #domain x size
l2 = 10.0;      #domain y size
a = 1.0;        #hole radius
σ0 = 1.0;       #traction load
E = 1000;       #Young modulus
ν = 0.3;        #Poisson ratio

meshSize = 0.5/5;
#meshSize = 0.2/5;
surfaceMeshSize = meshSize;
minNeighbors = 10;
minSearchRadius = meshSize;

μ = 0.5*E/(1+ν);      #Lamè coefficients
λ = E*ν/((1+ν)*(1-2*ν));


#read pointcloud from a SU2 file
time1 = time();
pointcloud = ElasticArray{Float64}(undef,2,0);      #2xN matrix containing the coordinates [X;Y] of each node
boundaryNodes = Vector{Int}(undef,0);       #indices of the boundary nodes
internalNodes = Vector{Int}(undef,0);       #indices of the internal nodes
normals = ElasticArray{Float64}(undef,2,0);     #2xN matrix containing the components [nx;ny] of the normal of each boundary node

pointcloud = parseSU2mesh("18c_2d_hole_plate_mesh_1207.su2");
#pointcloud = parseSU2mesh("18c_2d_hole_plate_mesh_6981.su2");
cornerPoint = findall((pointcloud[1,:].==a).*(pointcloud[2,:].==0));
#deleteat!.(pointcloud, Ref(cornerPoint));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
cornerPoint = findall((pointcloud[1,:].==l1).*(pointcloud[2,:].==0));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
cornerPoint = findall((pointcloud[1,:].==l1).*(pointcloud[2,:].==l2));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
cornerPoint = findall((pointcloud[1,:].==0).*(pointcloud[2,:].==l2));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
cornerPoint = findall((pointcloud[1,:].==0).*(pointcloud[2,:].==a));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
cornerPoint = findall((pointcloud[1,:].==0).*(pointcloud[2,:].==0));
#pointcloud = pointcloud[:, 1:end .!= cornerPoint];
pointcloud = pointcloud[:, setdiff(1:end,cornerPoint)];
N = size(pointcloud,2);

for i=1:N
    if (pointcloud[1,i].^2+pointcloud[2,i].^2).<=(a+1e-5)^2
        #hole
        push!(boundaryNodes, i);
        append!(normals, -pointcloud[:,i]/a);
    elseif pointcloud[1,i]>=l1-1e-5
        #right
        push!(boundaryNodes, i);
        append!(normals, [1,0]);
    elseif pointcloud[1,i]<=0+1e-5
        #left
        push!(boundaryNodes, i);
        append!(normals, [-1,0]);
    elseif pointcloud[2,i]>=l2-1e-5
        #top
        push!(boundaryNodes, i);
        append!(normals, [0,1]);
    elseif pointcloud[2,i]<=0+1e-5
        #bottom
        push!(boundaryNodes, i);
        append!(normals, [0,-1]);
    else
        #internal
        push!(internalNodes, i);
        append!(normals, [0,0]);
    end
end
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));


#boundary conditions
N = size(pointcloud,2);     #number of 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]>=l1-1e-5
        #right - tx=σ0
        g1u[i] = 0.0;
        g2u[i] = 1.0;
        g3u[i] = σ0;
        g1v[i] = 0.0;
        g2v[i] = 1.0;
        g3v[i] = 0.0;
    elseif pointcloud[1,i]<=0+1e-5
        #left - u=0
        g1u[i] = 1.0;
        g2u[i] = 0.0;
        g3u[i] = 0.0;
        g1v[i] = 0.0;
        g2v[i] = 1.0;
        g3v[i] = 0.0;
    elseif pointcloud[2,i]<=0+1e-5
        #bottom - v=0
        g1u[i] = 0.0;
        g2u[i] = 1.0;
        g3u[i] = 0.0;
        g1v[i] = 1.0;
        g2v[i] = 0.0;
        g3v[i] = 0.0;
    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);


#neighbor search
time2 = time();
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
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


#least square matrix inversion
C = Vector{Matrix}(undef,N);       #stencil coefficients matrices
condV = zeros(N);
condC = zeros(N);
for i in internalNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,2+2*Nneighbors[i],12);
    for j=1:Nneighbors[i]
        V[j,:] = [1, xj[j], yj[j], xj[j]^2, yj[j]^2, xj[j]*yj[j],  0, 0, 0, 0, 0, 0];
        V[j+Nneighbors[i],:] = [0, 0, 0, 0, 0, 0,  1, xj[j], yj[j], xj[j]^2, yj[j]^2, xj[j]*yj[j]];
    end
    V[1+2*Nneighbors[i],:] = [0, 0, 0, 2*(2+λ/μ), 2, 0,  0, 0, 0, 0, 0, 1+λ/μ];
    V[2+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 1+λ/μ,  0, 0, 0, 2, 2*(2+λ/μ), 0];
    W = Diagonal(vcat(w[i],w[i],wpde,wpde));
    #(Q,R) = qr(W*V);
    #C[i] = inv(R)*transpose(Matrix(Q))*W;
    VF = svd(W*V);
    C[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
    condV[i] = cond(V);
    condC[i] = cond(C[i]);
end
for i in boundaryNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,4+2*Nneighbors[i],12);
    for j=1:Nneighbors[i]
        V[j,:] = [1, xj[j], yj[j], xj[j]^2, yj[j]^2, xj[j]*yj[j],  0, 0, 0, 0, 0, 0];
        V[j+Nneighbors[i],:] = [0, 0, 0, 0, 0, 0,  1, xj[j], yj[j], xj[j]^2, yj[j]^2, xj[j]*yj[j]];
    end
    V[1+2*Nneighbors[i],:] = [0, 0, 0, 2*(2+λ/μ), 2, 0,  0, 0, 0, 0, 0, 1+λ/μ];
    V[2+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 1+λ/μ,  0, 0, 0, 2, 2*(2+λ/μ), 0];
    V[3+2*Nneighbors[i],:] = [g1u[i], g2u[i]*normals[1,i]*(2+λ/μ), g2u[i]*normals[2,i], 0, 0, 0,  0, g2u[i]*normals[2,i], g2u[i]*normals[1,i]*λ/μ, 0, 0, 0];
    V[4+2*Nneighbors[i],:] = [0, g2v[i]*normals[2,i]*λ/μ, g2v[i]*normals[1,i], 0, 0, 0,  g1v[i], g2v[i]*normals[1,i], g2v[i]*normals[2,i]*(2+λ/μ), 0, 0, 0];
    W = Diagonal(vcat(w[i],w[i],wpde,wpde,wbc,wbc));
    #(Q,R) = qr(W*V);
    #C[i] = inv(R)*transpose(Matrix(Q))*W;
    VF = svd(W*V);
    C[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
    condV[i] = cond(V);
    condC[i] = cond(C[i]);
end
println("Inverted least-squares matrices in ", round(time()-time3,digits=2), " s");
println("Matrix properties:");
println("  Max cond(V): ",maximum(condV));
println("  Avg cond(V): ",sum(condV)/N);
println("  Min cond(V): ",minimum(condV));
println("  Max cond(C): ",maximum(condC));
println("  Avg cond(C): ",sum(condC)/N);
println("  Min cond(C): ",minimum(condC));

#condition number distribution
#=figure();
plt.hist(condC,10);
title("Condition number distribution");
xlabel("cond(C)");
ylabel("Absolute frequency");
display(gcf());=#


#matrix assembly
time4 = time();
rows = Int[];
cols = Int[];
vals = Float64[];
for i=1:N
    #u equation
    push!(rows, i);
    push!(cols, i);
    push!(vals, 1);
    for j=1:Nneighbors[i]
        push!(rows, i);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][1,j]);
        push!(rows, i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -C[i][1,j+Nneighbors[i]]);
    end
    #v equation
    push!(rows, N+i);
    push!(cols, N+i);
    push!(vals, 1);
    for j=1:Nneighbors[i]
        push!(rows, N+i);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][7,j]);
        push!(rows, N+i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -C[i][7,j+Nneighbors[i]]);
    end
end
M = sparse(rows,cols,vals,2*N,2*N);
println("Completed matrix assembly in ", round(time()-time4,digits=2), " s");


#linear system solution
time5 = time();
b = zeros(2*N);       #rhs vector
for i=1:N
    b[i] = 0;
    b[N+i] = 0;
    b[i] += -C[i][1,1+2*Nneighbors[i]]*Fx[i]/μ -C[i][1,2+2*Nneighbors[i]]*Fy[i]/μ;       #volumetric loads
    b[N+i] += -C[i][7,1+2*Nneighbors[i]]*Fx[i]/μ -C[i][7,2+2*Nneighbors[i]]*Fy[i]/μ;
end
for i in boundaryNodes
    b[i] += C[i][1,end-1]*g3u[i]/μ + C[i][1,end]*g3v[i]/μ;
    b[N+i] += C[i][7,end-1]*g3u[i]/μ + C[i][7,end]*g3v[i]/μ;
end
sol = M\b;
#using IterativeSolvers, IncompleteLU;
#LUM = ilu(M,τ=0.1);
#sol = bicgstabl(M,b,2,Pl=LUM,max_mv_products=2000,verbose=true);
println("Linear system solved in ", round(time()-time5,digits=2), " s");


#displacement plot
u = sol[1:N];
v = sol[N+1:end];
#=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());=#


#post-processing - σxx stress
dudx = zeros(N);
dvdy = zeros(N);
σxx = zeros(N);
for i=1:N
    for j=1:Nneighbors[i]
        dudx[i] += C[i][2,j]*u[neighbors[i][j]] + C[i][2,j+Nneighbors[i]]*v[neighbors[i][j]];
        dvdy[i] += C[i][9,j]*u[neighbors[i][j]] + C[i][9,j+Nneighbors[i]]*v[neighbors[i][j]];
    end
end
for i in boundaryNodes
    dudx[i] += C[i][2,3+2*Nneighbors[i]]*g3u[i]/μ + C[i][2,4+2*Nneighbors[i]]*g3v[i]/μ;
    dvdy[i] += C[i][9,3+2*Nneighbors[i]]*g3u[i]/μ + C[i][9,4+2*Nneighbors[i]]*g3v[i]/μ;
end
σxx = dudx*(2μ+λ) + dvdy*λ;

#stress plot
figure();
scatter(pointcloud[1,:],pointcloud[2,:],c=σxx,cmap="jet");
colorbar();
title("Hole plate - σxx stress");
axis("equal");
display(gcf());


#validation plot
idxPlot = findall(pointcloud[1,:].<=0+1e-5);
y_exact = collect(a:0.01:l1);
σxx_exact = @. σ0*(1- ((a^2)/(y_exact^2))*(-1.5+1)+1.5*((a^4)/(y_exact^4))*1);
figure();
plot(pointcloud[2,idxPlot],σxx[idxPlot],"r.",label="GFDM");
plot(y_exact,σxx_exact,"k-",linewidth=1.0,label="Analytical");
title("σxx stress @x=0");
legend(loc="upper right");
xlabel("y coordinate");
ylabel("σxx stress");
axis("equal");
display(gcf());

#error plot
y_exact = pointcloud[2,idxPlot];
σxx_exact = @. σ0*(1- ((a^2)/(y_exact^2))*(-1.5+1)+1.5*((a^4)/(y_exact^4))*1);
σxx_error = σxx[idxPlot]-σxx_exact;
figure();
plot(y_exact,σxx_error,"k-",linewidth=1.0);
title("Absolute error on σxx @y=0");
xlabel("x coordinate");
ylabel("σxx stress error");
display(gcf());
