annotate scripts/score_plot.py @ 1089:3de455e48d70

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