#----------------------------------------------------------------------
#  Direct GFDM method test - 2d rod thermal analysis
#  Author: Andrea Pavan
#  Date: 28/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 = 1.0;       #domain y size
k = 0.1;        #thermal conductivity
Tleft = 20;     #temperature on the left edge
Tright = 100;       #temperature on the right edge

meshSize = 0.2;
#meshSize = 0.025;
surfaceMeshSize = meshSize;
minNeighbors = 8;
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
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
g1 = zeros(Float64,N);
g2 = zeros(Float64,N);
g3 = zeros(Float64,N);
for i in boundaryNodes
    if pointcloud[1,i]<=0+1e-6
        #left surface
        g1[i] = 1.0;
        g2[i] = 0.0;
        g3[i] = Tleft;
    elseif pointcloud[1,i]>=l1-1e-6
        #right surface
        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


#stencil coefficients - Direct GFDM
C = Vector{Matrix}(undef,N);        #stencil coefficients matrices
condC = zeros(N);       #stencil condition number
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));
    VF = svd(W*V);
    C[i] = transpose(VF.Vt)*inv(Diagonal(VF.S))*transpose(VF.U)*W;
    condC[i] = cond(C[i]);
end
for i in boundaryNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    nx = normals[1,i];
    ny = normals[2,i];
    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]*nx, g2[i]*ny, 0, 0, 0];
    W = Diagonal(vcat(w[i],wpde,wbc));
    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
    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] += g3[i];
end
u = qr(M)\b;
println("Linear system solved in ", round(time()-time5,digits=2), " s");


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


#M-matrix verification
M
isZmatrix = true;
isLmatrix = true;
isSDD = true;
isWDD = true;
for i=1:N
    if isZmatrix
        for j=1:N
            if i!=j && M[i,j]>0
                global isZmatrix = false;
                global isLmatrix = false;
            end
        end
        if M[i,i]<=0
            global isLmatrix = false;
        end
    end
    if abs(M[i,i])-sum(abs.(M[i,:]))<0
        global isWDD = false;
        global isSDD = false;
    elseif abs(M[i,i])-sum(abs.(M[i,:]))==0
        global isSDD = false;
    end
end
isMmatrix = isSDD.*isLmatrix;
println("Sparse M matrix properties:");
println("  Z-matrix: ",isZmatrix);
println("  L-matrix: ",isLmatrix);
println("  Strictly diagonal dominant: ",isSDD);
println("  Weakly diagonal dominant: ",isWDD);
println("  M-matrix: ",isMmatrix);
