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