annotate scripts/score_plot.py @ 1365:c4156df1dcb5

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