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