#----------------------------------------------------------------------
#  Direct GFDM method test - 2d Laplace equation, Mixed BC
#  Validation: https://pythonawesome.com/finite-difference-solution-of-2d-poisson-equation/
#  Author: Andrea Pavan
#  Date: 21/12/2022
#  License: GPLv3-or-later
#----------------------------------------------------------------------
using ElasticArrays;
using LinearAlgebra;
using SparseArrays;
using PyPlot;
include("utils.jl");


#problem definition
l1 = 12.0;      #domain x size
l2 = 6.0;       #domain y size
function uD(x,y)        #Dirichlet boundary conditions
    if x!=0 && y!=0 && x!=l1 && y!=l2
        return 1.5;
    end
    return 0.0;
end
gN(x,y) = 0.0;      #Neumann boundary conditions

meshSize = 0.2;     #distance target between internal nodes
surfaceMeshSize = 0.2;      #distance target between boundary nodes
minNeighbors = 8;       #minimum number of neighbors allowed
minSearchRadius = meshSize/2;       #starting search radius


#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
dirichletNodes = Vector{Int}(undef,0);       #indices of the Dirichlet nodes
neumannNodes = Vector{Int}(undef,0);     #indices of the Neumann 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:l1
    append!(pointcloud, [i,0.0]);
    append!(normals, [0,-1]);
    push!(dirichletNodes, size(pointcloud,2));
end
for i=surfaceMeshSize:surfaceMeshSize:l2
    append!(pointcloud, [l1,i]);
    append!(normals, [1,0]);
    push!(neumannNodes, size(pointcloud,2));
end
for i=l1-surfaceMeshSize:-surfaceMeshSize:0
    append!(pointcloud, [i,l2]);
    append!(normals, [0,1]);
    push!(neumannNodes, size(pointcloud,2));
end
for i=l2-surfaceMeshSize:-surfaceMeshSize:surfaceMeshSize
    append!(pointcloud, [0,i]);
    append!(normals, [-1,0]);
    push!(neumannNodes, size(pointcloud,2));
end
for x=7.0:meshSize:7.4
    for y=2.5:meshSize:3.2
        append!(pointcloud, [x,y]);
        append!(normals, [0,0]);
        push!(dirichletNodes, size(pointcloud,2));
    end
end
boundaryNodes = collect(range(1,size(pointcloud,2)));
for x=0+meshSize:meshSize:l1-meshSize
    for y=0+meshSize:meshSize:l2-meshSize
        #P = [x,y];
        P = [x,y]+(rand(Float64,2).-0.5).*meshSize/5;

        #check if P is too close to the boundary
        insertP = true;
        for j in boundaryNodes
            if (x-pointcloud[1,j])^2+(y-pointcloud[2,j])^2<(0.75*meshSize)^2
                insertP = false;
            end
        end
        if insertP
            append!(pointcloud, P);
        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(1);
plot(pointcloud[1,dirichletNodes],pointcloud[2,dirichletNodes],"r.");
plot(pointcloud[1,neumannNodes],pointcloud[2,neumannNodes],"b.");
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
w2 = 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]);
    w2[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]
        w2[i][j] = exp(-1*r2[i][j]/r2max)^2;
    end
end
w2pde = 2.0;        #least squares weight for the pde
w2bc = 2.0;     #least squares weight for the boundary condition


#least square matrix inversion
A = Vector{Matrix}(undef,N);        #least-squares matrices
#condA = Vector{Float64}(undef,N);       #condition number
C = Vector{Matrix}(undef,N);        #derivatives coefficients matrices
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[end,:] = [0, 0, 0, 2, 2, 0];
    W = Diagonal(vcat(w2[i],w2pde));
    A[i] = transpose(V)*W*V;
    #condA[i] = cond(A[i]);
    (Q,R) = qr(A[i]);
    C[i] = inv(R)*transpose(Q)*transpose(V)*W;
    #C[i] = inv(transpose(V)*W*V)*transpose(V)*W;
    #C[i] = hcat(-sum(C[i],dims=2), C[i]);
end
for i in neumannNodes
    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[end-1,:] = [0, 0, 0, 2, 2, 0];
    V[end,:] = [0, normals[1,i], normals[2,i], 0, 0, 0];
    W = Diagonal(vcat(w2[i],[w2pde,w2bc]));
    A[i] = transpose(V)*W*V;
    #condA[i] = cond(A[i]);
    (Q,R) = qr(A[i]);
    C[i] = inv(R)*transpose(Q)*transpose(V)*W;
    #C[i] = inv(transpose(V)*W*V)*transpose(V)*W;
    #C[i] = hcat(-sum(C[i],dims=2), C[i]);
end
for i in dirichletNodes
    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[end-1,:] = [0, 0, 0, 2, 2, 0];
    V[end,:] = [1, 0, 0, 0, 0, 0];
    W = Diagonal(vcat(w2[i],[w2pde,w2bc]));
    A[i] = transpose(V)*W*V;
    #condA[i] = cond(A[i]);
    (Q,R) = qr(A[i]);
    C[i] = inv(R)*transpose(Q)*transpose(V)*W;
    #C[i] = inv(transpose(V)*W*V)*transpose(V)*W;
    #C[i] = hcat(-sum(C[i],dims=2), C[i]);
end
println("Inverted least-squares matrices in ", round(time()-time3,digits=2), " s");


#matrix assembly
time4 = time();
rows = Int[];
cols = Int[];
vals = Float64[];
for i in dirichletNodes
    push!(rows, i);
    push!(cols, i);
    push!(vals, 1);
    for j=1:lastindex(neighbors[i])
        push!(rows, i);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][1,j]);
    end
end
for i in neumannNodes
    push!(rows, i);
    push!(cols, i);
    push!(vals, 1);
    for j=1:lastindex(neighbors[i])
        push!(rows, i);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][1,j]);
    end
end
for i in internalNodes
    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 dirichletNodes
    b[i] = C[i][1,end]*uD(pointcloud[1,i],pointcloud[2,i]);
end
for i in neumannNodes
    b[i] = 0;
end
for i in internalNodes
    b[i] = 0;
end
u = M\b;
println("Linear system solved in ", round(time()-time5,digits=2), " s");

#solution plot
figure(4);
scatter(pointcloud[1,:],pointcloud[2,:],c=u,cmap="plasma");
colorbar();
title("Laplace equation - mixed BC");
axis("equal");
display(gcf());
