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