annotate python/score_plot.py @ 2450:c602b4c69310

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