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