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