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