annotate scripts/score_plot.py @ 1118:3edcbbea168b

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