annotate scripts/score_plot.py @ 22:1f375b7d75fd tip

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