annotate scripts/score_plot.py @ 1481:8be2d08fbe15

Started WAC paper
author Brecht De Man <b.deman@qmul.ac.uk>
date Tue, 22 Sep 2015 19:22:02 +0200
parents
children 18dc725bb5c2 1b6fa37d46a4 235594325b84
rev   line source
b@1481 1 #!/usr/bin/python
b@1481 2
b@1481 3 import sys
b@1481 4 import os
b@1481 5 import csv
b@1481 6 import matplotlib.pyplot as plt
b@1481 7 import numpy as np
b@1481 8 import scipy as sp
b@1481 9 import scipy.stats
b@1481 10
b@1481 11 # COMMAND LINE ARGUMENTS
b@1481 12
b@1481 13 #TODO: Merge, implement this functionality
b@1481 14 #TODO: Control by CLI arguments (plot types, save and/or show, ...)
b@1481 15
b@1481 16 assert len(sys.argv)<4, "score_plot takes at most 2 command line arguments\n"+\
b@1481 17 "Use: python score_plot.py [ratings_folder_location]."+\
b@1481 18 "Type 'python score_plot.py -h' for more options"
b@1481 19
b@1481 20 # initialise plot types (false by default) and options
b@1481 21 enable_boxplot = False # show box plot
b@1481 22 enable_confidence = False # show confidence interval
b@1481 23 confidence = 0.90 # confidence value (for confidence interval plot)
b@1481 24 enable_individual = False # show all individual ratings
b@1481 25 show_individual = [] # show specific individuals (empty: show all individuals found)
b@1481 26 show_legend = False # show names of individuals
b@1481 27
b@1481 28 # DEFAULT: Looks in 'saves/ratings/' folder from 'scripts/' folder
b@1481 29 rating_folder = "../saves/ratings/"
b@1481 30
b@1481 31 # XML results files location
b@1481 32 if len(sys.argv) == 1: # no extra arguments
b@1481 33 enable_boxplot = True # show box plot
b@1481 34 print "Use: python score_plot.py [rating folder] [plot_type] [-l/-legend]"
b@1481 35 print "Type 'python score_plot.py -h' for help."
b@1481 36 print "Using default path: " + rating_folder + " with boxplot."
b@1481 37 else:
b@1481 38 for arg in sys.argv: # go over all arguments
b@1481 39 if arg == '-h':
b@1481 40 # show help
b@1481 41 #TODO: replace with contents of helpfile score_plot.info (or similar)
b@1481 42 print "Use: python score_plot.py [rating_folder] [plot_type] [-l] [confidence]"
b@1481 43 print " rating_folder:"
b@1481 44 print " folder where output of 'score_parser' can be found, and"
b@1481 45 print " where plots will be stored."
b@1481 46 print " By default, '../saves/ratings/' is used."
b@1481 47 print ""
b@1481 48 print "PLOT TYPES"
b@1481 49 print " Can be used in combination."
b@1481 50 print " box | boxplot | -b"
b@1481 51 print " Enables the boxplot"
b@1481 52 print " conf | confidence | -c"
b@1481 53 print " Enables the confidence interval plot"
b@1481 54 print " ind | individual | -i"
b@1481 55 print " Enables plot of individual ratings"
b@1481 56 print ""
b@1481 57 print "PLOT OPTIONS"
b@1481 58 print " leg | legend | -l"
b@1481 59 print " For individual plot: show legend with individual file names"
b@1481 60 print " numeric value between 0 and 1, e.g. 0.95"
b@1481 61 print " For confidence interval plot: confidence value"
b@1481 62 assert False, ""# stop immediately after showing help #TODO cleaner way
b@1481 63
b@1481 64 # PLOT TYPES
b@1481 65 elif arg == 'box' or arg == 'boxplot' or arg == '-b':
b@1481 66 enable_boxplot = True # show box plot
b@1481 67 elif arg == 'conf' or arg == 'confidence' or arg == '-c':
b@1481 68 enable_confidence = True # show confidence interval
b@1481 69 #TODO add confidence value input
b@1481 70 elif arg == 'ind' or arg == 'individual' or arg == '-i':
b@1481 71 enable_individual = True # show all individual ratings
b@1481 72
b@1481 73 # PLOT OPTIONS
b@1481 74 elif arg == 'leg' or arg == 'legend' or arg == '-l':
b@1481 75 if not enable_individual:
b@1481 76 print "WARNING: The 'legend' option is only relevant to plots of "+\
b@1481 77 "individual ratings"
b@1481 78 show_legend = True # show all individual ratings
b@1481 79 elif arg.isdigit():
b@1481 80 if not enable_confidence:
b@1481 81 print "WARNING: The numeric confidence value is only relevant when "+\
b@1481 82 "confidence plot is enabled"
b@1481 83 if float(arg)>0 and float(arg)<1:
b@1481 84 confidence = float(arg)
b@1481 85 else:
b@1481 86 print "WARNING: The confidence value needs to be between 0 and 1"
b@1481 87
b@1481 88 # FOLDER NAME
b@1481 89 else:
b@1481 90 # assume it's the folder name
b@1481 91 rating_folder = arg
b@1481 92
b@1481 93 # at least one plot type should be selected: box plot by default
b@1481 94 if not enable_boxplot and not enable_confidence and not enable_individual:
b@1481 95 enable_boxplot = True
b@1481 96
b@1481 97 # check if folder_name exists
b@1481 98 if not os.path.exists(rating_folder):
b@1481 99 #the file is not there
b@1481 100 print "Folder '"+rating_folder+"' does not exist."
b@1481 101 sys.exit() # terminate script execution
b@1481 102 elif not os.access(os.path.dirname(rating_folder), os.W_OK):
b@1481 103 #the file does exist but write rating_folder are not given
b@1481 104 print "No write privileges in folder '"+rating_folder+"'."
b@1481 105
b@1481 106
b@1481 107 # CONFIGURATION
b@1481 108
b@1481 109 # Font settings
b@1481 110 font = {'weight' : 'bold',
b@1481 111 'size' : 10}
b@1481 112 plt.rc('font', **font)
b@1481 113
b@1481 114
b@1481 115 # CODE
b@1481 116
b@1481 117 # get every csv file in folder
b@1481 118 for file in os.listdir(rating_folder): # You have to put this in folder where rating csv files are.
b@1481 119 if file.endswith(".csv"):
b@1481 120 page_name = file[:-4] # file name (without extension) is page ID
b@1481 121
b@1481 122 # get header
b@1481 123 with open(rating_folder+file, 'rb') as readfile: # read this csv file
b@1481 124 filereader = csv.reader(readfile, delimiter=',')
b@1481 125 headerrow = filereader.next() # use headerrow as X-axis
b@1481 126 headerrow = headerrow[1:]
b@1481 127
b@1481 128 # read ratings into matrix
b@1481 129 # ratings = np.loadtxt(open(rating_folder+file,"rb"),
b@1481 130 # delimiter=",",
b@1481 131 # skiprows=1,
b@1481 132 # usecols=range(1,len(headerrow)+1)
b@1481 133 # )
b@1481 134 ratings = np.genfromtxt(readfile,
b@1481 135 delimiter=",",
b@1481 136 #skip_header = 1,
b@1481 137 converters = {3: lambda s: float(s or 'Nan')},
b@1481 138 usecols=range(1,len(headerrow)+1)
b@1481 139 )
b@1481 140
b@1481 141 # assert at least 2 subjects (move on to next file if violated)
b@1481 142 if ratings.shape[0]<2:
b@1481 143 print "WARNING: Just one subject for " + page_name + ". Moving on to next file."
b@1481 144 break
b@1481 145
b@1481 146 # BOXPLOT
b@1481 147 if enable_boxplot:
b@1481 148 plt.boxplot(ratings)
b@1481 149
b@1481 150 # CONFIDENCE INTERVAL
b@1481 151 if enable_confidence:
b@1481 152 iterator = 0
b@1481 153 for column in ratings.T: # iterate over transposed matrix
b@1481 154 # remove all 'Nan's from column
b@1481 155 column = column[~np.isnan(column)]
b@1481 156
b@1481 157 # get number of non-Nan ratings (= #subjects)
b@1481 158 n = column.size
b@1481 159
b@1481 160 # get mean
b@1481 161 mean_rating = np.mean(column)
b@1481 162
b@1481 163 # get errors
b@1481 164 err = scipy.stats.sem(column)* sp.stats.t._ppf((1+confidence)/2., n-1)
b@1481 165
b@1481 166 # draw plot
b@1481 167 plt.errorbar(iterator+1,
b@1481 168 mean_rating,
b@1481 169 yerr=err,
b@1481 170 marker="x",
b@1481 171 color ="k",
b@1481 172 markersize=12,
b@1481 173 linestyle='None')
b@1481 174
b@1481 175 iterator += 1 # increase counter
b@1481 176
b@1481 177
b@1481 178 # INDIVIDUAL PLOT
b@1481 179 if enable_individual or show_individual:
b@1481 180 # marker list and color map to cycle through
b@1481 181 markerlist = ["x", ".", "o", "*", "+", "v", ">", "<", "8", "s", "p"]
b@1481 182 colormap = ['b', 'r', 'g', 'c', 'm', 'y', 'k']
b@1481 183 increment = 0
b@1481 184 linehandles = []
b@1481 185 legendnames = []
b@1481 186 with open(rating_folder+file, 'rb') as readfile: # read this csv file
b@1481 187 filereader = csv.reader(readfile, delimiter=',')
b@1481 188 headerrow = filereader.next() # use headerrow as X-axis
b@1481 189 headerrow = headerrow[1:]
b@1481 190 for row in filereader:
b@1481 191 subject_id = row[0][:-4] # read from beginning of line
b@1481 192 # assume plotting all individuals if no individual(s) specified
b@1481 193 if not show_individual or subject_id in show_individual:
b@1481 194 plothandle, = plt.plot(range(1,len(row)), # x-values
b@1481 195 ratings[increment,:],#row[1:], # y-values: csv values except subject name
b@1481 196 color=colormap[increment%len(colormap)],
b@1481 197 marker=markerlist[increment%len(markerlist)],
b@1481 198 markersize=10,
b@1481 199 linestyle='None',
b@1481 200 label=subject_id
b@1481 201 )
b@1481 202 linehandles.append(plothandle)
b@1481 203 legendnames.append(subject_id)
b@1481 204 if show_legend:
b@1481 205 plt.legend(linehandles, legendnames,
b@1481 206 loc='upper right',
b@1481 207 bbox_to_anchor=(1.1, 1),
b@1481 208 borderaxespad=0.,
b@1481 209 numpoints=1 # remove extra marker
b@1481 210 )
b@1481 211 increment += 1 # increase counter
b@1481 212
b@1481 213 # TITLE, AXIS LABELS AND LIMITS
b@1481 214 plt.title(page_name)
b@1481 215 plt.xlabel('Fragment')
b@1481 216 plt.xlim(0, len(headerrow)+1) # only show relevant region, leave space left & right)
b@1481 217 plt.xticks(range(1, len(headerrow)+1), headerrow, rotation=90) # show fragment names
b@1481 218 plt.ylabel('Rating')
b@1481 219 plt.ylim(0,1)
b@1481 220
b@1481 221
b@1481 222
b@1481 223 # SHOW PLOT
b@1481 224 #plt.show()
b@1481 225 #exit()
b@1481 226
b@1481 227 # SAVE PLOT
b@1481 228 # automatically
b@1481 229 plot_type = ("-box" if enable_boxplot else "") + \
b@1481 230 ("-conf" if enable_confidence else "") + \
b@1481 231 ("-ind" if enable_individual else "")
b@1481 232 plt.savefig(rating_folder+page_name+plot_type+".pdf", bbox_inches='tight')
b@1481 233 plt.close()