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