annotate scripts/score_plot.py @ 2072:49b03ad3dcf9

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