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