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