import sys, getopt, os, subprocess, math, random
import numpy as np
import scipy.stats, scipy.spatial
import networkx as nx
import utils, gdv_utils, plot_utils, pr_roc_utils, draw_utils, model_utils, pca_utils
import settings


gnuplotTemplate = file(settings.GNUPLOT_SCATTER_TEMPLATE_FILE, 'r').read()

input_sub_dir = ''
figure_format_list = ['png']

opts, args = getopt.getopt(sys.argv[1:], "s:f:h", ["subdir=","help"])
for o, a in opts:
    if o in ('-s', '--subdir'):
        input_sub_dir = a  + '/'
    elif o in ('-f'):
        figure_format_list = a.split(',')
    elif o in ('-h','--help'):
        print """Usage:
%s model_name_list statc_output_dir
-s,--subdir          Input/output subdirectory
-f                   Figure format (e.g., eps or png)
-h,--help            Print this""" % sys.argv[0]
        sys.exit(0)

model_name_list = args[0].split(',')
stat_output_dir = args[1]

stat_plot_dir = settings.BASE_OUTPUT_DIR +'MODEL_ANALYSIS/%s/stat/plots/' % stat_output_dir

print 'Obtaining network lists...'

network_name_list = []
model_network_file_list = {}
aggregated_network_file_list = []
for model_name in model_name_list:
    model_dir = settings.BASE_INPUT_DIR + input_sub_dir + 'model/%s/%s/' % (model_utils.getModelType(model_name),model_name)
    #for each model, get all random instances
    new_networks = [name for name in os.listdir(model_dir) if os.path.isdir(os.path.join(model_dir, name))]
    network_name_list += new_networks

    model_network_file_list[model_name] = []
    for n in new_networks:
        model_network_file_list[model_name].append(model_dir + '%s/aggregated/%s_aggregated_1.txt' % (n,n))
    aggregated_network_file_list += model_network_file_list[model_name]




#edge count
print 'Performing edge counting...'
model_edge_counts = {}
aggregated_edge_counts = []
for model_name in model_network_file_list:
    model_edge_counts[model_name] = []
    for n in model_network_file_list[model_name]:
        G = nx.read_edgelist(n)
        model_edge_counts[model_name].append(G.size())
    aggregated_edge_counts += model_edge_counts[model_name]


draw_params = {
    'title': '',
    'prop_title': 'Edges',
    'number_of_bins': 20,
}

print 'Generating figures...'
for figure_format in figure_format_list:
    #per model
    for model_name in model_edge_counts:
        draw_utils.draw_values_histogram(model_edge_counts[model_name],stat_plot_dir + '%s/per_model/' % figure_format,  model_name + '_edges', format = figure_format, params = draw_params)

    #for all combined
    draw_utils.draw_values_histogram(aggregated_edge_counts,stat_plot_dir + '%s/' % figure_format,  stat_output_dir + '_edges', format = figure_format, params = draw_params)



