#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Make statistics on score files (stored in JSON files).
"""

import common_functions as common

import argparse
import json
#import math
import os

import matplotlib.pyplot as plt
import numpy as np

# histtype : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’]
HIST_TYPE='bar'
ALPHA=0.5


def extract_score_list(json_dict, score_index):
    io_list = json_dict["io"]
    json_data = [image_dict["score"][score_index] for image_dict in io_list if "score" in image_dict]
    return json_data

if __name__ == '__main__':

    # PARSE OPTIONS ###########################################################

    parser = argparse.ArgumentParser(description="Make statistics on score files (JSON files).")

    parser.add_argument("--logx", "-l", action="store_true", default=False,
                        help="Use a logaritmic scale on the X axis")

    parser.add_argument("--logy", "-L", action="store_true", default=False,
                        help="Use a logaritmic scale on the Y axis")

    parser.add_argument("--tight", action="store_true", default=False,
                        help="Optimize the X axis usage")

    parser.add_argument("--max", "-m", type=float, default=None, metavar="FLOAT", 
                        help="The maximum abscissa value to plot")

    parser.add_argument("--index", "-i", type=int, default=0, metavar="INT", 
                        help="The index of the score to plot in case of multivalued scores")

    parser.add_argument("--overlaid", "-O", action="store_true", default=False,
                        help="Overlaid histograms")

    parser.add_argument("--output", "-o", default=None,
                        metavar="FILE",
                        help="The output file path")

    parser.add_argument("--title", default=None,
                        metavar="STRING",
                        help="The title of the plot")

    parser.add_argument("--quiet", "-q", action="store_true",
                        help="Don't show the plot, just save it")

    parser.add_argument("fileargs", nargs="+", metavar="FILE",
                        help="The JSON file to process")

    args = parser.parse_args()

    logx = args.logx
    logy = args.logy
    tight = args.tight
    max_abscissa = args.max
    score_index = args.index
    overlaid = args.overlaid
    title = args.title
    quiet = args.quiet
    json_file_path_list = args.fileargs

    if args.output is None:
        suffix1 = "_i" + str(score_index)
        suffix2 = "_o" if overlaid else ""
        suffix3 = "_" + str(max_abscissa) if max_abscissa is not None else ""
        output_file_path = "scores{}{}{}.pdf".format(suffix1, suffix2, suffix3)
    else:
        output_file_path = args.output

    # FETCH SCORE #############################################################

    data_list = []
    label_list = []

    for json_file_path in json_file_path_list:
        json_dict = common.parse_json_file(json_file_path)

        score_list = extract_score_list(json_dict, score_index)

        if max_abscissa is not None:
            score_list = [score for score in score_list if score <= max_abscissa]

        data_list.append(np.array(score_list))

        label_list.append(json_dict["label"])

    # PLOT STATISTICS #########################################################

    fig, ax1 = plt.subplots(nrows=1, ncols=1, figsize=(10, 6))

    common.plot_hist1d(ax1,
                       data_list,
                       label_list=label_list,
                       logx=logx,
                       logy=logy,
                       xmax=max_abscissa,
                       overlaid=overlaid,
                       xlabel="Score",
                       title=title,
                       num_bins=30,
                       tight=tight)

    # Save file and plot ########

    plt.savefig(output_file_path, bbox_inches='tight')

    if not quiet:
        plt.show()


@@ -336,210 +336,8 @@
 5%0A%0A%0A
-def extract_score_list(json_dict, score_index):%0A    io_list = json_dict%5B%22io%22%5D%0A    json_data = %5Bimage_dict%5B%22score%22%5D%5Bscore_index%5D for image_dict in io_list if %22score%22 in image_dict%5D%0A    return json_data%0A%0A
 if _
@@ -997,14 +997,8 @@
 ax%22,
- %22-m%22,
  typ
@@ -1137,42 +1137,61 @@
 (%22--
-index
+metric
 %22, %22-
-i%22, type=int, default=0,
+m%22, required=True,%0A                       
  met
@@ -1200,14 +1200,16 @@
 ar=%22
+STR
 IN
-T
+G
 %22,
- 
 %0A   
@@ -1243,64 +1243,27 @@
 The 
-index of the score to plot in case of multivalued scores
+metric name to plot
 %22)%0A%0A
@@ -2070,37 +2070,8 @@
 max%0A
-    score_index = args.index%0A
     
@@ -2118,16 +2118,41 @@
 s.title%0A
+    metric = args.metric%0A
     quie
@@ -2259,29 +2259,18 @@
 = %22_
-i
 %22 + 
-str(score_index)
+metric
 %0A   
@@ -2685,16 +2685,71 @@
 h_list:%0A
+        print(%22Parsing %7B%7D...%22.format(json_file_path))%0A%0A
         
@@ -2808,29 +2808,84 @@
         
-score_list = 
+print(len(json_dict%5B%22io%22%5D), %22images%22)%0A%0A        score_array = common.
 extract_
@@ -2890,20 +2890,21 @@
 t_score_
-list
+array
 (json_di
@@ -2911,19 +2911,14 @@
 ct, 
-score_index
+metric
 )%0A%0A 
@@ -2971,23 +2971,33 @@
   score_
-list = 
+array = np.array(
 %5Bscore f
@@ -3014,20 +3014,21 @@
 n score_
-list
+array
  if scor
@@ -3045,16 +3045,17 @@
 bscissa%5D
+)
 %0A%0A      
@@ -3077,28 +3077,19 @@
 end(
-np.array(
 score_
-list)
+array
 )%0A%0A 

Update a plot script.