#----------------------------------------------------------------------
#  GFDM method test - 2d rod thermal analysis + mechanical post-proc
#  Author: Andrea Pavan
#  Date: 29/01/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 = 1.0;       #domain y size
E = 71.7e9;     #Young modulus
ν = 0.33;       #Poisson ratio
α = 23.6e-6;        #thermal expansion coefficient
k = 140;        #thermal conductivity
Tref = 20;      #thermal expansion reference temperature
Tright = 100;       #right side temperature
Tleft = 20;        #left side temperature

meshSize = 0.2;
#meshSize = 0.0625;
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
    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));


#boundary conditions
N = size(pointcloud,2);     #number of nodes
g1 = zeros(Float64,N);
g2 = zeros(Float64,N);
g3 = zeros(Float64,N);
for i in boundaryNodes
    if pointcloud[1,i]<=0+1e-6
        #left side
        g1[i] = 1.0;
        g2[i] = 0.0;
        g3[i] = Tleft;
    elseif pointcloud[1,i]>=l1-1e-6
        #left side
        g1[i] = 1.0;
        g2[i] = 0.0;
        g3[i] = Tright;
    else
        #everywhere else
        g1[i] = 0.0;
        g2[i] = 1.0;
        g3[i] = 0.0;
    end
end

#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();
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
condC = zeros(N);
for i in internalNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,1+Nneighbors[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
    V[1+Nneighbors[i],:] = [0, 0, 0, 2, 2, 0];
    W = Diagonal(vcat(w[i],wpde));
    (Q,R) = qr(W*V);
    C[i] = inv(R)*transpose(Matrix(Q))*W;
    #condC[i] = cond(C[i]);
end
for i in boundaryNodes
    #println("Boundary node: ",i);
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,2+Nneighbors[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
    V[1+Nneighbors[i],:] = [0, 0, 0, 2, 2, 0];
    V[2+Nneighbors[i],:] = [g1[i], g2[i]*normals[1,i], g2[i]*normals[2,i], 0, 0, 0];
    W = Diagonal(vcat(w[i],wpde,wbc));
    (Q,R) = qr(W*V);
    C[i] = inv(R)*transpose(Matrix(Q))*W;
    #condC[i] = cond(C[i]);
end
println("Inverted least-squares matrices in ", round(time()-time3,digits=2), " s");
#=println("Matrix properties:");
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
    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]);
    end
end
M = sparse(rows,cols,vals,N,N);
println("Completed matrix assembly in ", round(time()-time4,digits=2), " s");


#linear system solution
time5 = time();
b = zeros(N);       #rhs vector
for i in internalNodes
    b[i] = 0;
end
for i in boundaryNodes
    b[i] = C[i][1,end]*g3[i];
end
T = M\b;
println("Linear system solved in ", round(time()-time5,digits=2), " s");

#thermal solution plot
figure();
plt = scatter(pointcloud[1,:],pointcloud[2,:],c=T,cmap="inferno");
title("Numerical solution - temperature");
axis("equal");
colorbar(plt);
display(gcf());


#post-processing - heat fluxes
dTdx = Vector{Float64}(undef,N);
dTdy = Vector{Float64}(undef,N);
qx = Vector{Float64}(undef,N);
qy = Vector{Float64}(undef,N);
for i=1:N
    dTdx[i] = 0.0;
    dTdy[i] = 0.0;
    for j=1:Nneighbors[i]
        dTdx[i] += C[i][2,j]*T[neighbors[i][j]];        #C[i][j]*u[j]
        dTdy[i] += C[i][3,j]*T[neighbors[i][j]];
    end
    #dTdx[i] += C[i][2,1+Nneighbors[i]]*0;       #C[i][1+N]*gPDE
    #dTdy[i] += C[i][3,1+Nneighbors[i]]*0;
end
for i in boundaryNodes
    dTdx[i] += C[i][2,2+Nneighbors[i]]*g3[i];       #C[i][2+N]*gBC
    dTdy[i] += C[i][3,2+Nneighbors[i]]*g3[i];
end
qx = -k*dTdx;
qy = -k*dTdy;

#heat fluxes plot
#=figure();
plt = scatter(pointcloud[1,:],pointcloud[2,:],c=qx,cmap="hsv");
title("Numerical solution - qx heat flux");
axis("equal");
colorbar(plt);
display(gcf());=#


#mechanical post-processing - boundary conditions
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;
    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


#mechanical post-processing - least square matrix inversion
Fx = -E*α*dTdx/(1-ν);       #volumetric load due to the temperature gradient
Fy = -E*α*dTdy/(1-ν);
Cm = Vector{Matrix}(undef,N);       #stencil coefficients matrices
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*1/(1-ν^2), 2*0.5*1/(1+ν), 0,  0, 0, 0, 0, 0, 1*ν/(1-ν^2)+0.5*1/(1+ν)];
    V[2+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 1*ν/(1-ν^2)+0.5*1/(1+ν),  0, 0, 0, 2*0.5*1/(1+ν), 2*1/(1-ν^2), 0];
    W = Diagonal(vcat(w[i],w[i],wpde,wpde));
    VF = svd(W*V);
    Cm[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
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*1/(1-ν^2), 2*0.5*1/(1+ν), 0,  0, 0, 0, 0, 0, 1*ν/(1-ν^2)+0.5*1/(1+ν)];
    V[2+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 1*ν/(1-ν^2)+0.5*1/(1+ν),  0, 0, 0, 2*0.5*1/(1+ν), 2*1/(1-ν^2), 0];
    V[3+2*Nneighbors[i],:] = [g1u[i], g2u[i]*normals[1,i]*1/(1-ν^2), g2u[i]*normals[2,i]*0.5*1/(1+ν), 0, 0, 0,  0, g2u[i]*normals[2,i]*0.5*1/(1+ν), g2u[i]*normals[1,i]*1*ν/(1-ν^2), 0, 0, 0];
    V[4+2*Nneighbors[i],:] = [0, g2v[i]*normals[2,i]*1*ν/(1-ν^2), g2v[i]*normals[1,i]*0.5*1/(1+ν), 0, 0, 0,  g1v[i], g2v[i]*normals[1,i]*0.5*1/(1+ν), g2v[i]*normals[2,i]*1/(1-ν^2), 0, 0, 0];
    W = Diagonal(vcat(w[i],w[i],wpde,wpde,wbc,wbc));
    VF = svd(W*V);
    Cm[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
end
println("Inverted least-squares matrices");


#mechanical post-processing - matrix assembly
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, -Cm[i][1,j]);
        push!(rows, i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -Cm[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, -Cm[i][7,j]);
        push!(rows, N+i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -Cm[i][7,j+Nneighbors[i]]);
    end
end
Mm = sparse(rows,cols,vals,2*N,2*N);
println("Completed matrix assembly");


#mechanical post-processing - linear system solution
bm = zeros(2*N);       #rhs vector
for i=1:N
    bm[i] = 0;
    bm[N+i] = 0;
    bm[i] += -Cm[i][1,1+2*Nneighbors[i]]*Fx[i]/E -Cm[i][1,2+2*Nneighbors[i]]*Fy[i]/E;
    bm[N+i] += -Cm[i][7,1+2*Nneighbors[i]]*Fx[i]/E -Cm[i][7,2+2*Nneighbors[i]]*Fy[i]/E;
end
for i in boundaryNodes
    bm[i] += Cm[i][1,end-1]*(g3u[i]/E + g2u[i]*normals[1,i]*1*α*(T[i]-Tref)/(1-ν)) + Cm[i][1,end]*(g3v[i]/E + g2v[i]*normals[2,i]*1*α*(T[i]-Tref)/(1-ν));
    bm[N+i] += Cm[i][7,end-1]*(g3u[i]/E + g2u[i]*normals[1,i]*1*α*(T[i]-Tref)/(1-ν)) + Cm[i][7,end]*(g3v[i]/E + g2v[i]*normals[2,i]*1*α*(T[i]-Tref)/(1-ν));
    #bm[i] += Cm[i][1,end-1]*g3u[i]/E + Cm[i][1,end]*g3v[i]/E;
    #bm[N+i] += Cm[i][7,end-1]*g3u[i]/E + Cm[i][7,end]*g3v[i]/E;
end
sol = Mm\bm;
println("Linear system solved");

#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());

println("\nAnalytic:");
println("> umax = ",l1*α*(maximum(T)-Tref));
println("> Tmax = 100.0");
println("GFDM:");
println("> umax = ",maximum(abs.(u)));
println("> vmax = ",maximum(abs.(v)));
println("> Tmax = ",maximum(abs.(T)));


println("\nCalculiX FEM:");
println("> umax = 0.01390");
println("> vmax = 0.001168");
println("> Tmax = 100.0");
println("GFDM:");
println("> umax = ",maximum(abs.(u)));
println("> vmax = ",maximum(abs.(v)));
println("> Tmax = ",maximum(abs.(T)));
