using LightGraphs 
using MetaGraphs
using LinearAlgebra
using SparseArrays
using SuiteSparse
using Combinatorics

include("./misc.jl")

function read_sparsity_pattern(instance_path::String)
    data = load_matpower(instance_path)
    ## Bus load and shunt information
    i_debut, i_fin = find_numarray(1, data)
    checkfor(data, i_debut-1, "mpc.bus")
    nb_bus = i_fin-i_debut+1
    index_bus = Dict( data[i+i_debut-1,1] => i for i=1:nb_bus)
    ## Bus generator information
    i_debut, i_fin = find_numarray(i_fin+1, data)
    checkfor(data, i_debut-1, "mpc.gen")
    #initialize network graph G
    sp = spzeros(nb_bus,nb_bus)
    ## Link information
    i_debut, i_fin = find_numarray(i_fin+1, data)
    checkfor(data, i_debut-1, "mpc.branch")
    for i=i_debut:i_fin
        if data[i, 11] == 0
        else
            orig = index_bus[data[i,1]]
            dest = index_bus[data[i,2]]
            sp[orig,dest] = 1
        end
    end
    sp_sym = sp + sp'
    diag = zeros(nb_bus)
    for i=1:nb_bus
        sum_col = sum(sp_sym[i,:])
        diag[i] = Int(sum_col + 1)
    end
    return sp_sym + Diagonal(diag)
end


function read_sparsity_pattern(graph::AbstractGraph)
    sparsity_pattern = adjacency_matrix(graph)
    for i in 1:nv(graph)
        sparsity_pattern[i, i] = length(neighbors(graph, i)) + 1
    end
    return sparsity_pattern
end
