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