annotate scripts/score_plot.py @ 1099:0a15fa67bda1

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