annotate scripts/score_plot.py @ 718:0b095f66de65

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