giuliomoro@15: #!/usr/bin/python giuliomoro@15: giuliomoro@15: import sys giuliomoro@15: import os giuliomoro@15: import csv giuliomoro@15: import matplotlib.pyplot as plt giuliomoro@15: import numpy as np giuliomoro@15: import scipy as sp giuliomoro@15: import scipy.stats giuliomoro@15: giuliomoro@15: # COMMAND LINE ARGUMENTS giuliomoro@15: giuliomoro@15: #TODO: Merge, implement this functionality giuliomoro@15: #TODO: Control by CLI arguments (plot types, save and/or show, ...) giuliomoro@15: giuliomoro@15: assert len(sys.argv)<4, "score_plot takes at most 2 command line arguments\n"+\ giuliomoro@15: "Use: python score_plot.py [ratings_folder_location]."+\ giuliomoro@15: "Type 'python score_plot.py -h' for more options" giuliomoro@15: giuliomoro@15: # initialise plot types (false by default) and options giuliomoro@15: enable_boxplot = False # show box plot giuliomoro@15: enable_confidence = False # show confidence interval giuliomoro@15: confidence = 0.90 # confidence value (for confidence interval plot) giuliomoro@15: enable_individual = False # show all individual ratings giuliomoro@15: show_individual = [] # show specific individuals (empty: show all individuals found) giuliomoro@15: show_legend = False # show names of individuals giuliomoro@15: giuliomoro@15: # DEFAULT: Looks in 'saves/ratings/' folder from 'scripts/' folder giuliomoro@15: rating_folder = "../saves/ratings/" giuliomoro@15: giuliomoro@15: # XML results files location giuliomoro@15: if len(sys.argv) == 1: # no extra arguments giuliomoro@15: enable_boxplot = True # show box plot giuliomoro@15: print("Use: python score_plot.py [rating folder] [plot_type] [-l/-legend]") giuliomoro@15: print("Type 'python score_plot.py -h' for help.") giuliomoro@15: print("Using default path: " + rating_folder + " with boxplot.") giuliomoro@15: else: giuliomoro@15: for arg in sys.argv: # go over all arguments giuliomoro@15: if arg == '-h': giuliomoro@15: # show help giuliomoro@15: #TODO: replace with contents of helpfile score_plot.info (or similar) giuliomoro@15: print("Use: python score_plot.py [rating_folder] [plot_type] [-l] [confidence]") giuliomoro@15: print(" rating_folder:") giuliomoro@15: print(" folder where output of 'score_parser' can be found, and") giuliomoro@15: print(" where plots will be stored.") giuliomoro@15: print(" By default, '../saves/ratings/' is used.") giuliomoro@15: print("") giuliomoro@15: print("PLOT TYPES") giuliomoro@15: print(" Can be used in combination.") giuliomoro@15: print(" box | boxplot | -b") giuliomoro@15: print(" Enables the boxplot" ) giuliomoro@15: print(" conf | confidence | -c") giuliomoro@15: print(" Enables the confidence interval plot" ) giuliomoro@15: print(" ind | individual | -i") giuliomoro@15: print(" Enables plot of individual ratings" ) giuliomoro@15: print("") giuliomoro@15: print("PLOT OPTIONS") giuliomoro@15: print(" leg | legend | -l") giuliomoro@15: print(" For individual plot: show legend with individual file names") giuliomoro@15: print(" numeric value between 0 and 1, e.g. 0.95") giuliomoro@15: print(" For confidence interval plot: confidence value") giuliomoro@15: assert False, ""# stop immediately after showing help #TODO cleaner way giuliomoro@15: giuliomoro@15: # PLOT TYPES giuliomoro@15: elif arg == 'box' or arg == 'boxplot' or arg == '-b': giuliomoro@15: enable_boxplot = True # show box plot giuliomoro@15: elif arg == 'conf' or arg == 'confidence' or arg == '-c': giuliomoro@15: enable_confidence = True # show confidence interval giuliomoro@15: #TODO add confidence value input giuliomoro@15: elif arg == 'ind' or arg == 'individual' or arg == '-i': giuliomoro@15: enable_individual = True # show all individual ratings giuliomoro@15: giuliomoro@15: # PLOT OPTIONS giuliomoro@15: elif arg == 'leg' or arg == 'legend' or arg == '-l': giuliomoro@15: if not enable_individual: giuliomoro@15: print("WARNING: The 'legend' option is only relevant to plots of "+\ giuliomoro@15: "individual ratings") giuliomoro@15: show_legend = True # show all individual ratings giuliomoro@15: elif arg.isdigit(): giuliomoro@15: if not enable_confidence: giuliomoro@15: print("WARNING: The numeric confidence value is only relevant when "+\ giuliomoro@15: "confidence plot is enabled") giuliomoro@15: if float(arg)>0 and float(arg)<1: giuliomoro@15: confidence = float(arg) giuliomoro@15: else: giuliomoro@15: print("WARNING: The confidence value needs to be between 0 and 1") giuliomoro@15: giuliomoro@15: # FOLDER NAME giuliomoro@15: else: giuliomoro@15: # assume it's the folder name giuliomoro@15: rating_folder = arg giuliomoro@15: giuliomoro@15: # at least one plot type should be selected: box plot by default giuliomoro@15: if not enable_boxplot and not enable_confidence and not enable_individual: giuliomoro@15: enable_boxplot = True giuliomoro@15: giuliomoro@15: # check if folder_name exists giuliomoro@15: if not os.path.exists(rating_folder): giuliomoro@15: #the file is not there giuliomoro@15: print("Folder '"+rating_folder+"' does not exist.") giuliomoro@15: sys.exit() # terminate script execution giuliomoro@15: elif not os.access(os.path.dirname(rating_folder), os.W_OK): giuliomoro@15: #the file does exist but write rating_folder are not given giuliomoro@15: print("No write privileges in folder '"+rating_folder+"'.") giuliomoro@15: giuliomoro@15: giuliomoro@15: # CONFIGURATION giuliomoro@15: giuliomoro@15: # Font settings giuliomoro@15: font = {'weight' : 'bold', giuliomoro@15: 'size' : 10} giuliomoro@15: plt.rc('font', **font) giuliomoro@15: giuliomoro@15: giuliomoro@15: # CODE giuliomoro@15: giuliomoro@15: # get every csv file in folder giuliomoro@15: for file in os.listdir(rating_folder): giuliomoro@15: if file.endswith(".csv"): giuliomoro@15: page_name = file[:-4] # file name (without extension) is page ID giuliomoro@15: giuliomoro@15: # get header (as text) giuliomoro@15: with open(rating_folder+file, 'rt') as readfile: # read this csv file giuliomoro@15: filereader = csv.reader(readfile, delimiter=',') giuliomoro@15: headerrow = next(filereader) # use headerrow as X-axis giuliomoro@15: headerrow = headerrow[1:] giuliomoro@15: giuliomoro@15: # read ratings into matrix (as bytes) giuliomoro@15: with open(rating_folder+file, 'rb') as readfile: # read this csv file giuliomoro@15: filereader = csv.reader(readfile, delimiter=',') giuliomoro@15: ratings = np.genfromtxt(readfile, giuliomoro@15: delimiter=",", giuliomoro@15: skip_header = 1, giuliomoro@15: converters = {3: lambda s: float(s or 'Nan')}, giuliomoro@15: usecols=list(range(1,len(headerrow)+1)) giuliomoro@15: ) giuliomoro@15: giuliomoro@15: # assert at least 2 subjects (move on to next file if violated) giuliomoro@15: if ratings.shape[0]<2: giuliomoro@15: print("WARNING: Just one subject for " + page_name + ". Moving on to next file.") giuliomoro@15: break giuliomoro@15: giuliomoro@15: # BOXPLOT giuliomoro@15: if enable_boxplot: giuliomoro@15: plt.boxplot(ratings) giuliomoro@15: giuliomoro@15: # CONFIDENCE INTERVAL giuliomoro@15: if enable_confidence: giuliomoro@15: iterator = 0 giuliomoro@15: for column in ratings.T: # iterate over transposed matrix giuliomoro@15: # remove all 'Nan's from column giuliomoro@15: column = column[~np.isnan(column)] giuliomoro@15: giuliomoro@15: # get number of non-Nan ratings (= #subjects) giuliomoro@15: n = column.size giuliomoro@15: giuliomoro@15: # get mean giuliomoro@15: mean_rating = np.mean(column) giuliomoro@15: giuliomoro@15: # get errors giuliomoro@15: err = scipy.stats.sem(column)* sp.stats.t._ppf((1+confidence)/2., n-1) giuliomoro@15: giuliomoro@15: # draw plot giuliomoro@15: plt.errorbar(iterator+1, giuliomoro@15: mean_rating, giuliomoro@15: yerr=err, giuliomoro@15: marker="x", giuliomoro@15: color ="k", giuliomoro@15: markersize=12, giuliomoro@15: linestyle='None') giuliomoro@15: giuliomoro@15: iterator += 1 # increase counter giuliomoro@15: giuliomoro@15: giuliomoro@15: # INDIVIDUAL PLOT giuliomoro@15: if enable_individual or show_individual: giuliomoro@15: # marker list and color map to cycle through giuliomoro@15: markerlist = ["x", ".", "o", "*", "+", "v", ">", "<", "8", "s", "p"] giuliomoro@15: colormap = ['b', 'r', 'g', 'c', 'm', 'y', 'k'] giuliomoro@15: increment = 0 giuliomoro@15: linehandles = [] giuliomoro@15: legendnames = [] giuliomoro@15: with open(rating_folder+file, 'r') as readfile: # read this csv file giuliomoro@15: filereader = csv.reader(readfile, delimiter=',') giuliomoro@15: headerrow = next(filereader) # use headerrow as X-axis giuliomoro@15: headerrow = headerrow[1:] giuliomoro@15: for row in filereader: giuliomoro@15: subject_id = row[0][:-4] # read from beginning of line giuliomoro@15: # assume plotting all individuals if no individual(s) specified giuliomoro@15: if not show_individual or subject_id in show_individual: giuliomoro@15: plothandle, = plt.plot(range(1,len(row)), # x-values giuliomoro@15: ratings[increment,:],#row[1:], # y-values: csv values except subject name giuliomoro@15: color=colormap[increment%len(colormap)], giuliomoro@15: marker=markerlist[increment%len(markerlist)], giuliomoro@15: markersize=10, giuliomoro@15: linestyle='None', giuliomoro@15: label=subject_id giuliomoro@15: ) giuliomoro@15: linehandles.append(plothandle) giuliomoro@15: legendnames.append(subject_id) giuliomoro@15: if show_legend: giuliomoro@15: plt.legend(linehandles, legendnames, giuliomoro@15: loc='upper right', giuliomoro@15: bbox_to_anchor=(1.1, 1), giuliomoro@15: borderaxespad=0., giuliomoro@15: numpoints=1 # remove extra marker giuliomoro@15: ) giuliomoro@15: increment += 1 # increase counter giuliomoro@15: giuliomoro@15: # TITLE, AXIS LABELS AND LIMITS giuliomoro@15: plt.title(page_name) giuliomoro@15: plt.xlabel('Fragment') giuliomoro@15: plt.xlim(0, len(headerrow)+1) # only show relevant region, leave space left & right) giuliomoro@15: plt.xticks(range(1, len(headerrow)+1), headerrow, rotation=90) # show fragment names giuliomoro@15: plt.ylabel('Rating') giuliomoro@15: plt.ylim(0,1) giuliomoro@15: giuliomoro@15: giuliomoro@15: giuliomoro@15: # SHOW PLOT giuliomoro@15: #plt.show() giuliomoro@15: #exit() giuliomoro@15: giuliomoro@15: # SAVE PLOT giuliomoro@15: # automatically giuliomoro@15: plot_type = ("-box" if enable_boxplot else "") + \ giuliomoro@15: ("-conf" if enable_confidence else "") + \ giuliomoro@15: ("-ind" if enable_individual else "") giuliomoro@15: plt.savefig(rating_folder+page_name+plot_type+".pdf", bbox_inches='tight') giuliomoro@15: plt.close()