#----------------------------------------------------------------------
#  Direct MDLSM method test - 2d heat equation, Mixed BC, Steady solver
#  2d rectangular beam between two fixed temperatures
#  Author: Andrea Pavan
#  Date: 06/02/2023
#  License: GPLv3-or-later
#----------------------------------------------------------------------
using ElasticArrays;
using LinearAlgebra;
using SparseArrays;
using PyPlot;
include("utils.jl");


#problem definition
l1 = 1.0;       #domain x size
l2 = 0.1;       #domain y size
uL = 300;       #left border temperature
uR = 400;       #right border temperature
k = 5.0;        #thermal conductivity
ρ = 8.0;        #density
cp = 3.8;       #specific heat capacity

meshSize = 0.02;
surfaceMeshSize = meshSize;
minNeighbors = 5;
minSearchRadius = meshSize/2;


#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:l2
    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-5
        #left border
        g1[i] = 1.0;
        g2[i] = 0.0;
        g3[i] = uL;
    elseif pointcloud[1,i]>=l1-1e-5
        #right border
        g1[i] = 1.0;
        g2[i] = 0.0;
        g3[i] = uR;
    else
        #everywhere else
        g1[i] = 0.0;
        g2[i] = 1.0;
        g3[i] = 0.0;
    end
end


#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);       #stencil conditioning
for i in internalNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,3+3*Nneighbors[i],9);
    for j=1:Nneighbors[i]
        V[j,:] = [1, xj[j], yj[j], 0, 0, 0, 0, 0, 0];
        V[j+Nneighbors[i],:] = [0, 0, 0, 1, xj[j], yj[j], 0, 0, 0];
        V[j+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 0, 1, xj[j], yj[j]];
    end
    V[1+3*Nneighbors[i],:] = [0, 0, 0,  0, 1, 0,  0, 0, 1];
    V[2+3*Nneighbors[i],:] = [0, k, 0,  1, 0, 0,  0, 0, 0];
    V[3+3*Nneighbors[i],:] = [0, 0, k,  0, 0, 0,  1, 0, 0];
    W = Diagonal(vcat(w[i],w[i],w[i],wpde,wpde,wpde));
    (Q,R) = qr(W*V);
    C[i] = inv(R)*transpose(Matrix(Q))*W;
    condC[i] = cond(C[i]);
end
for i in boundaryNodes
    xj = P[i][1,:];
    yj = P[i][2,:];
    V = zeros(Float64,4+3*Nneighbors[i],9);
    for j=1:Nneighbors[i]
        V[j,:] = [1, xj[j], yj[j], 0, 0, 0, 0, 0, 0];
        V[j+Nneighbors[i],:] = [0, 0, 0, 1, xj[j], yj[j], 0, 0, 0];
        V[j+2*Nneighbors[i],:] = [0, 0, 0, 0, 0, 0, 1, xj[j], yj[j]];
    end
    V[1+3*Nneighbors[i],:] = [0, 0, 0,  0, 1, 0,  0, 0, 1];
    V[2+3*Nneighbors[i],:] = [0, k, 0,  1, 0, 0,  0, 0, 0];
    V[3+3*Nneighbors[i],:] = [0, 0, k,  0, 0, 0,  1, 0, 0];
    V[4+3*Nneighbors[i],:] = [k*g1[i], 0, 0,  -g2[i]*normals[1,i], 0, 0,  -g2[i]*normals[2,i], 0, 0];
    W = Diagonal(vcat(w[i],w[i],w[i],wpde,wpde,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("  Max condition number: ",round(maximum(condC),digits=2));
println("  Avg condition number: ",round(sum(condC)/N,digits=2));
println("  Min condition number: ",round(minimum(condC),digits=2));


#matrix assembly
time4 = time();
rows = Int[];
cols = Int[];
vals = Float64[];
#rows = Vector{Int}(undef,3*N);
#cols = Vector{Int}(undef,3*N);
#vals = Vector{Float64}(undef,3*N);
for i=1:N
    #u equation
    push!(rows, i);
    push!(cols, i);
    push!(vals, 1);
    for j=1:Nneighbors[i]
        #u terms
        push!(rows, i);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][1,j]);
        #qx terms
        push!(rows, i);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -C[i][1,j+Nneighbors[i]]);
        #qy terms
        push!(rows, i);
        push!(cols, 2*N+neighbors[i][j]);
        push!(vals, -C[i][1,j+2*Nneighbors[i]]);
    end

    #qx equation
    push!(rows, i+N);
    push!(cols, i+N);
    push!(vals, 1);
    for j=1:Nneighbors[i]
        #u terms
        push!(rows, i+N);
        push!(cols, neighbors[i][j]);
        push!(vals, -C[i][4,j]);
        #qx terms
        push!(rows, i+N);
        push!(cols, N+neighbors[i][j]);
        push!(vals, -C[i][4,j+Nneighbors[i]]);
        #qy terms
        push!(rows, i+N);
        push!(cols, 2*N+neighbors[i][j]);
        push!(vals, -C[i][4,j+2*Nneighbors[i]]);
    end

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


#linear system solution
time5 = time();
b = zeros(3*N);     #rhs vector
for i in internalNodes
    b[i] = 0 + 0 + 0;
    b[i+N] = 0 + 0 + 0;
    b[i+2*N] = 0 + 0 + 0;
end
for i in boundaryNodes
    b[i] = 0 + 0 + 0 + C[i][1,end]*k*g3[i];
    b[i+N] = 0 + 0 + 0 + C[i][4,end]*k*g3[i];
    b[i+2*N] = 0 + 0 + 0 + C[i][7,end]*k*g3[i];
end
sol = M\b;
u = sol[1:N];
qx = sol[N+1:2*N];
qy = sol[2*N+1:3*N];
println("Linear system solved in ", round(time()-time5,digits=2), " s");

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