annotate scripts/score_plot.py @ 1457:c8a9825aaa05

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