-
Notifications
You must be signed in to change notification settings - Fork 0
/
mazetracker.py
1299 lines (1128 loc) · 41.2 KB
/
mazetracker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# Mazetrack Data Analyzer TODO :
# [LOW] Entry Box with points listed, ability to edit points, delete last point
# [MED] When File Selecting... Make the ability to navigate within folders (WIN32)
# Identify Center of Polygon
# File Load/Save folder locations dialog, WINDOWS?!
# Grab Ap Image file from video frame Linux - Done Windows - BROKE!!!
# Initial Directory = Working Directroy
from os import *
from Tkinter import *
from PIL import Image
import ImageTk
import ImageDraw
import xlrd
import tkFileDialog
import string, time
from math import *
import tkMessageBox
import gst
import shutil
points = []
#Dicts to Hold Summary Data
sum_disp = {}
sum_duration = {}
sum_reachgoal = {}
sum_ccorrect = {}
sum_cwrong = {}
pixcmratio = 0
pwd = ""
apimageloc = ""
pwd_saves = ""
#########################################################################
#MENU FUNCTIONS
#########################################################################
def menu_imageselect():
global ApImage
global temp
global apimageloc
global pwd_saves
filestr = tkFileDialog.askopenfilename(title='Please select image:', filetypes = [('png images', '.png'), ('gif images', '.gif'), ('jpg images', '.jpg')])
#pilfilestr = '"' + filestr + '"'
pilimage = Image.open(filestr)
ApImage = ImageTk.PhotoImage(pilimage)
temp = can.create_image(176,144, image = ApImage)
l_pwd.config(text=filestr)
apimageloc = filestr
tempfilestr = filestr.rsplit("/",1)
pwd_saves = tempfilestr[0] + "/"
print "PWD SAVES:", pwd_saves
def menu_imageselectavi():
global ApImage
global temp
global apimageloc
global pwd_saves
filestr = tkFileDialog.askopenfilename(title='Please select avi:', filetypes = [('avi files', '.avi')])
print "AVI FILESTR:", filestr
filestrsplit = filestr.rsplit('.', 1)
theoreticalstr = filestrsplit[0] + "-apparatus.png"
if path.exists(theoreticalstr) == False:
imfilestr = '"' + filestr + '"'
gfilename, gpwd = grabimframe(imfilestr)
pilfilestr = gpwd + gfilename
shutil.move(gfilename, gpwd)
pilimage = Image.open(pilfilestr)
ApImage = ImageTk.PhotoImage(pilimage)
temp = can.create_image(176,144, image = ApImage)
l_pwd.config(text=pilfilestr)
apimageloc = pilfilestr
print "API-LOC", apimageloc
pwd = gpwd
pwd_saves = gpwd
elif path.exists(theoreticalstr) == True:
pilimage = Image.open(theoreticalstr)
ApImage = ImageTk.PhotoImage(pilimage)
temp = can.create_image(176,144, image = ApImage)
l_pwd.config(text=filestr)
apimageloc = filestr
tempfilestr = filestr.rsplit("/",1)
pwd_saves = tempfilestr[0] + "/"
print "PWD_SAVES", pwd_saves
#########################################################################
def menu_savedatafile():
filestr = tkFileDialog.asksaveasfilename(title='Saving MTA Zone File...:', filetypes = [('MTA Zone File', '.mta')])
#save entire listbox worth of zones
f = file(filestr,'w')
#print lbmainlist.get(0,END)
for each in lbmainlist.get(0,END):
#print each
f.writelines(each)
f.writelines('/n')
f.close()
#########################################################################
def menu_loaddatafile():
filestr = tkFileDialog.askopenfilename(title='Please select MTA settings:', filetypes = [('MTA Zone File', '.mta')])
f = file(filestr, 'r')
for line in f:
plistlines = string.split(line,'/n')
#print "processline:", plistlines
for item in plistlines:
if item != '':
entryline = item.split('[')
#print "SPLIT ENTRYLINE:", entryline
zonename = entryline[0]
#print "ZONENAME:", zonename
points = entryline[1]
#print "POINTS1:", points
points = '[' + points
#print "POINTS2:", points
lbmainlist.insert(END, (zonename, points))
else:
pass
f.close()
#########################################################################
def menu_instructions():
window3 = Toplevel()
window3.title("Instructions...")
filelist = Listbox(window2)
lzoneentry = Label(text= "Zone Name:")
def menu_about():
window4 = Toplevel()
window4.title("About Mazetrack Analyzer")
def menu_hello():
pass
#########################################################################
#########################################################################
#BUTTONS
#########################################################################
def bf_addzone():
global ApImage
global points
zonename = ezonename.get()
#points.append(points[0]) #FIX
#points.append(points[1])
temp = can.create_image(176,144, image = ApImage)
can.create_polygon(points, fill="", outline="black")
lbmainlist.insert(END, (zonename, points))
points = []
def bf_deletezone():
zonetodelete = lbmainlist.curselection()
lbmainlist.delete(zonetodelete)
temp = can.create_image(176,144, image = ApImage) #display image on canvas
def bf_showzone():
points = []
temp = can.create_image(176,144, image = ApImage)
#print "Redrawing Zone"
zonetodraw = lbmainlist.curselection()
zonedata = lbmainlist.get(zonetodraw)
points = eval(zonedata[1])
can.create_polygon(points, fill="", outline="black")
def bf_showall():
temp = can.create_image(176,144, image = ApImage)
points = []
#print "Redrawing Zone:", lbmainlist
temp_list = list(lbmainlist.get(0, END))
for each in temp_list:
zonedata = each
points = eval(zonedata[1])
can.create_text(points[0], points[1], text = zonedata[0], anchor = NW, fill = "red")
can.create_polygon(points, fill="", outline="black")
def bf_clearpoints():
global points
points = []
temp = can.create_image(176,144, image = ApImage)
def bf_excelselect():
global filelist
global window5
window5 = Toplevel()
window5.title("Select your excel worksheet:")
window5.geometry("+400+200")
filelist = Listbox(window5)
filelist.grid(row = 0, column = 0)
flist = listdir('./')
for item in flist:
filelist.insert(END,item)
filelist.bind("<Double-Button-1>",ef_excelload)
button = Button(window5, text="Close", command=window5.destroy)
button.grid(row = 1, column =0)
# IF WINDOWS IS DETECTED, USE THIS EXCEL ADD FUNCTION
if sys.platform == "win32":
#print "DETECTED WINDOWS:", sys.platform
def bf_exaddfile():
global exfilelist
global window6
window6 = Toplevel()
window6.title("Select file to add:")
window6.geometry("+400+400")
exfilelist = Listbox(window6)
exfilelist.grid(row = 0, column = 0)
flist = listdir('./')
flist.sort()
for item in flist:
if string.find(item,'.xls'):
exfilelist.insert(END,item)
exfilelist.bind("<Double-Button-1>",addtolist)
button = Button(window6, text="Close", command=window6.destroy)
button.grid(row = 1, column =0)
#FOR OTHER OS, USE THIS FUNCTION
else:
#print "DETECTED Other Platform:", sys.platform
def bf_exaddfile():
xlsfile = tkFileDialog.askopenfilenames(title='Please select files to add:', filetypes = [('excel files', '.xls')])
for filestr in xlsfile:
filelocation = filestr
filenametemp = filestr.split('/')
#print filenametemp
filename = filenametemp.pop()
filetuple = (filename, filelocation)
#print filetuple
lb_excelfiles.insert(END, filetuple)
def addtolist(self):
fileselection = exfilelist.curselection()
filestr = exfilelist.get(fileselection[0])
lb_excelfiles.insert(END, filestr)
def bf_exdelfile():
filetodelete = lb_excelfiles.curselection()
lb_excelfiles.delete(filetodelete)
def bf_expreview(self):
#bf_clearpoints()
rundata = []
fileselection = lb_excelfiles.curselection()
fileselection2 = lb_excelfiles.get(fileselection)
filetoload = fileselection2[1]
xlsfile = xlrd.open_workbook(filetoload)
sh = xlsfile.sheet_by_index(0)
num_datapoints = (sh.nrows-2)
#Strip String Stuff
firstrow = str(sh.row(0))
firstrow = firstrow.split(',')
processlist = []
for each in firstrow:
if each[1] == 't':
if each[0] == '[':
cellentry = each.lstrip("[text:u'")
cellentry = cellentry.rstrip("'")
processlist.append(cellentry)
else:
cellentry = each.lstrip(" text:u'")
cellentry = cellentry.rstrip("'")
processlist.append(cellentry)
elif each[1] == 'e':
cellentry = each.strip(" empty:u'")
cellentry = cellentry.strip("]")
processlist.append(cellentry)
elif each[1] == 'n':
cellentry = each.strip(" number:u")
cellentry = cellentry.strip("'")
processlist.append(cellentry)
rodentdata = []
currentcell = 0
#Initial Locations
#Time Point Locations
loc_time = (2, 0)
#X-Coord Locations
loc_xcoord = (2, 2)
#Y-Coord Locations
loc_ycoord = (2, loc_xcoord[1] + 2)
#Loop, Finding Data Points
while currentcell <= num_datapoints + 1:
#Set Points append to rodentdata
time = sh.cell_value(rowx=loc_time[0], colx=loc_time[1])
xcoord = sh.cell_value(rowx=loc_xcoord[0], colx=loc_xcoord[1])
ycoord = sh.cell_value(rowx=loc_ycoord[0], colx=loc_ycoord[1])
fudgefactorx = e_fudgex.get()
fudgefactory = e_fudgey.get()
ycoord = ycoord + int(fudgefactorx) # FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
xcoord = xcoord + int(fudgefactory) #FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
#Append to rodentdata
rodentdata.append((time,(ycoord, xcoord))) #FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
#Advance Locations
loc_time = (loc_time[0] + 1, loc_time[1])
loc_xcoord = (loc_xcoord[0] + 1, loc_xcoord[1])
loc_ycoord = (loc_ycoord[0] + 1, loc_ycoord[1])
currentcell = loc_time[0]
#End While Loop; Append to rundata
rundata.append(rodentdata)
#POINT TRACER
xcoords = []
ycoords = []
for each in rundata:
#print "RUNDATA:", each
for somepoints in each:
unpackpoint = somepoints[1]
xcoords.append(unpackpoint[0])
ycoords.append(unpackpoint[1])
while len(xcoords) > 0:
xpop = xcoords.pop(0)
ypop = ycoords.pop(0)
can.create_oval(xpop, ypop, xpop+1, ypop+1, fill="red")
#print xpop, ypop
#########################################################################
#########################################################################
#OTHER FUNCS
#########################################################################
def createPath(path):
if not os.path.isdir(path):
os.mkdir(path)
#CANVAS MOUSE CONTROLS
def zonecoords(event): # MOUSE 1 (LEFT-CLICK) PLACE POINT
can.create_oval(event.x, event.y, event.x+1, event.y+1, fill="black")
points.append(event.x)
points.append(event.y)
#print points
return points
def zonedraw(event): # MOUSE 3 (RIGHT-CLICK) GRAPH POINTS
global points
#print "Graphing!"
#points.append(points[0]) #Append 1st points to End to create polygon
#points.append(points[1]) #FIX - Make it so that it draws a seperate polygon from stored
can.create_polygon(points, fill="", outline="black")
#print points
# Addzone in the case of pressing <return> in zonename Entry box
def addzone(event):
global ApImage
global points
zonename = ezonename.get()
temp = can.create_image(176,144, image = ApImage)
lbmainlist.insert(END, (zonename, points))
points = []
#Showzone in the case of pressing <Button-3> on the lbmainlist listbox
def showzone(event):
temp = can.create_image(176,144, image = ApImage)
points = []
#print "Redrawing Zone"
zonetodraw = lbmainlist.curselection()
zonedata = lbmainlist.get(zonetodraw)
points = eval(zonedata[1])
can.create_polygon(points, fill="", outline="black")
def del_zoneitem(self): # FIX ACTIVATE
zonetodeletetemp = lbmainlist.curselection()
zonetodelete = int(zonetodeletetemp[0])
lbmainlist.delete(zonetodelete)
def del_excelitem(self): #FIX ACTIVATE
itemtodeletetemp = lb_excelfiles.curselection()
itemtodelete = int(itemtodeletetemp[0])
lb_excelfiles.delete(itemtodelete)
def lbxlsup(self):
itemtomovetemp = lb_excelfiles.curselection()
itemtomove = int(itemtomovetemp[0])
itemtoswap = int(itemtomove-1)
#print "item", itemtomove
if int(itemtomove) != 0:
temp1 = lb_excelfiles.get(itemtoswap)
temp2 = lb_excelfiles.get(itemtomove)
#print "temp1", temp1
#print "temp2", temp2
lb_excelfiles.delete(itemtoswap)
lb_excelfiles.insert(itemtoswap, temp2)
lb_excelfiles.delete(itemtomove)
lb_excelfiles.insert(itemtomove, temp1)
lb_excelfiles.activate(itemtomove)
def lbxlsdown(self):
lbxlsindex = lb_excelfiles.size()
#print "LB SIZE:", lbxlsindex
itemtomovetemp = lb_excelfiles.curselection()
itemtomove = int(itemtomovetemp[0])
itemtoswap = int(itemtomove+1)
#print "item", itemtomove
if int(itemtomove) < lbxlsindex-1:
temp1 = lb_excelfiles.get(itemtoswap)
temp2 = lb_excelfiles.get(itemtomove)
#print "temp1", temp1
#print "temp2", temp2
lb_excelfiles.delete(itemtoswap)
lb_excelfiles.insert(itemtoswap, temp2)
lb_excelfiles.delete(itemtomove)
lb_excelfiles.insert(itemtomove, temp1)
lb_excelfiles.activate(itemtomove)
#function to load the list of zones into option menu for selection
def bf_loadlanelist():
v_lanelist = ["None"]
templist = lbmainlist.get(0, END)
for each in templist:
v_lanelist.append(each)
om_lanechoices = OptionMenu(rootwindow, vom_lanechoices, *v_lanelist)
#print "LANE LIST", v_lanelist
om_lanechoices.place(x = 430, y = 410)
def bf_loadlanelist2(): #For Exit Zone
v_lanelist2 = ["None"]
templist = lbmainlist.get(0, END)
for each in templist:
v_lanelist2.append(each)
om_lanechoices2 = OptionMenu(rootwindow, vom_lanechoices2, *v_lanelist2)
#print "LANE LIST", v_lanelist
om_lanechoices2.place(x = 430, y = 460)
def bf_setrefpoint():
global points
global ref_distance
#find distance between two points
xpoints = points[2] - points[0]
ypoints = points[3] - points[1]
ref_distance = sqrt(pow(xpoints,2)+pow(ypoints,2))
messagestr = "The selected pixel distance =" + str(ref_distance) + " Pixels"
tkMessageBox.showinfo("Reference Distance", messagestr)
ve_setrefpoint.set(str(ref_distance))
e_setrefpoint.config(textvariable=ve_setrefpoint)
def bf_entercm():
global pixcmratio
cmdist = e_entercm.get()
ref_entry = e_setrefpoint.get()
print cmdist[0]
print ref_entry
pixcmratio = round(float(cmdist)/float(ref_entry), 4)
messagestr = "Calculated Pixel to cm Ratio =" + str(pixcmratio)
tkMessageBox.showinfo("Pixel to cm Ratio", messagestr)
def bf_deleteallzones():
lbmainlist.delete(0,END)
def bf_deleteallxls():
lb_excelfiles.delete(0,END)
def auto_entercm():
global pixcmratio
cmdist = e_entercm.get()
ref_entry = e_setrefpoint.get()
print cmdist[0]
print ref_entry
pixcmratio = round(float(cmdist)/float(ref_entry), 4)
#Function to determine whether a point is contained within the area of a polygon or not
def isinpolygon(xytuple,poly):
x = xytuple[0]
y = xytuple[1]
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
def create_runimage(runid, runname, dir_pwd_saves):
global rundata
#POINT TRACER
xcoords = []
ycoords = []
runim = Image.open(apimageloc)
draw = ImageDraw.Draw(runim)
for each in rundata[runid]:
unpackpoint = each[1]
xcoords.append(unpackpoint[0])
ycoords.append(unpackpoint[1])
while len(xcoords) > 0:
xpop = xcoords.pop(0)
ypop = ycoords.pop(0)
draw.point((xpop, ypop), fill="red")
jpegsave = str(runname) + ".jpg"
runim.save(jpegsave, "JPEG")
newlocation = dir_pwd_saves + jpegsave
shutil.move(jpegsave, newlocation)
del draw
del runim
def grabimframe(filelocation):
# Define your pipeline, just as you would at the command prompt.
# This is much easier than trying to create and link each gstreamer element in Python.
# This is great for pipelines that end with a filesink (i.e. there is no audible or visual output)
filestr1 = filelocation.rsplit('/',1)
filestr = filestr1[1].strip('"')
#print "GLOCATION:", filelocation
#print "STR1:", filestr1
#print "STR:", filestr
retfilelocation = filelocation.strip(filestr + '"')
filestr = filestr.rsplit(".",1)
filestr = filestr[0]
#build str for gst parse
gstparse = "filesrc location=" + filelocation + " ! decodebin ! ffmpegcolorspace ! pngenc ! filesink location=" + filestr + "-apparatus.png"
pipe = gst.parse_launch(gstparse)
# Get a reference to the pipeline's bus
bus = pipe.get_bus()
# Set the pipeline's state to PLAYING
pipe.set_state(gst.STATE_PLAYING)
# Listen to the pipeline's bus indefinitely until we receive a EOS (end of stream) message.
# This is a super important step, or the pipeline might not work as expected. For example,
# in my example pipeline above, the pngenc will not export an actual image unless you have
# this line of code. It just exports a 0 byte png file. So... don't forget this step.
bus.poll(gst.MESSAGE_EOS, -1)
retfilename = filestr + "-apparatus.png"
#print "RETURN", retfilename
#print "RETURN", retfilelocation
return retfilename, retfilelocation
#########################################################################
#########################################################################
#EXCEL FUNCS
def ef_excelload():
excelfiles = []
excelfilesdump = lb_excelfiles.get(0,END)
for each in excelfilesdump:
excelfiles.append(each[1]) #append just the file locations to process list
ef_excelprocess(excelfiles)
def ef_excelprocess(exfilenames):
global sum_disp
global sum_duration
global sum_reachgoal
global sum_ccorrect
global sum_cwrong
global rundata
rundata = []
rodentid = [] #Load XLS file names to tag rodentid TODO
filename = e_outputfile.get()
if filename == "":
filename = "Output"
#print "Filename:", filename
if pixcmratio == 0:
auto_entercm()
print "Fired Auto CM Generator"
summaries_struct = []
#Summaries Struct
#0 sum_runs
#0 Runs
#0 Duration
#1 Reach Goal?
#2 Correct
#3 Wrong
#4 Dist Traveled
#1 sum_trial
#0 Avg. Duration
#1 Total Right
#2 Total Wrong
#3 Avg. Dist Traveled
#Load File, Establish Working Sheet
for each in exfilenames:
runid = each.rsplit('/',1)
runid2 = runid[1].rsplit('.xls',1)
rodentid.append(runid2[0])
currentrodentid = runid2[0]
xlsfile = xlrd.open_workbook(each)
sh = xlsfile.sheet_by_index(0)
num_datapoints = (sh.nrows-2)
#Strip String Stuff
firstrow = str(sh.row(0))
firstrow = firstrow.split(',')
processlist = []
for each in firstrow:
if each[1] == 't':
if each[0] == '[':
cellentry = each.lstrip("[text:u'")
cellentry = cellentry.rstrip("'")
processlist.append(cellentry)
else:
cellentry = each.lstrip(" text:u'")
cellentry = cellentry.rstrip("'")
processlist.append(cellentry)
elif each[1] == 'e':
cellentry = each.strip(" empty:u'")
cellentry = cellentry.strip("]")
processlist.append(cellentry)
elif each[1] == 'n':
cellentry = each.strip(" number:u")
cellentry = cellentry.strip("'")
processlist.append(cellentry)
#############################################################################
#############################################################################
displacement = sh.cell_value(rowx=num_datapoints, colx=8) #grab displacement #FIX should be num_datapoints + 1 Mouse Tracker BUG
print "NUM_DATAPOITNS=", num_datapoints+1
print "DISPLACEMENT=", displacement
print "CMRATIO=", pixcmratio
if pixcmratio > 0:
sum_disp[currentrodentid] = round(displacement*pixcmratio,2)
else:
sum_disp[currentrodentid] = round(displacement,2)
rodentdata = []
currentcell = 0
#Initial Locations
#Time Point Locations
loc_time = (2, 0)
#X-Coord Locations
loc_xcoord = (2, 2)
#Y-Coord Locations
loc_ycoord = (2, loc_xcoord[1] + 2)
#Loop, Finding Data Points
while currentcell <= num_datapoints: #SHOULD BE +1 FIX, MOUSE TRACKER BUG
#Set Points append to rodentdata
time = sh.cell_value(rowx=loc_time[0], colx=loc_time[1])
xcoord = sh.cell_value(rowx=loc_xcoord[0], colx=loc_xcoord[1])
ycoord = sh.cell_value(rowx=loc_ycoord[0], colx=loc_ycoord[1])
fudgefactorx = e_fudgex.get()
fudgefactory = e_fudgey.get()
ycoord = ycoord + int(fudgefactorx) # FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
xcoord = xcoord + int(fudgefactory) #FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
#Append to rodentdata
rodentdata.append((time,(ycoord, xcoord))) #FIX Switched xcoord, ycoord to compensate for Mouse Tracker flaw
#Advance Locations
loc_time = (loc_time[0] + 1, loc_time[1])
loc_xcoord = (loc_xcoord[0] + 1, loc_xcoord[1])
loc_ycoord = (loc_ycoord[0] + 1, loc_ycoord[1])
currentcell = loc_time[0]
#End While Loop; Append to rundata
rundata.append(rodentdata)
#Analyis/Comparision of Results #Number of Times Entered Each Zone #Time to Find Zone/Platform #Time Spent in Zone
#load lbmain data and create polygons out of zonepoint data
zonelisttoprocess = []
listmain = lbmainlist.get(0,END)
for each in listmain:
zonename = each[0]
zonepoints = each[1]
zonepoints = eval(zonepoints) #convert to list
#zonepoints = zonepoints[:-2] #slice off copycat point #FIX
#build list contain for zone, zone points
zonepointsfinal = []
while zonepoints != []: #create list of tuples (polygon)
xp = zonepoints.pop(0)
yp = zonepoints.pop(0)
tupletime = (xp,yp)
zonepointsfinal.append(tupletime)
builttuple = (zonename, zonepointsfinal)
zonelisttoprocess.append(builttuple)
#print "ZoneList to Process:", zonelisttoprocess
zonelistcount = 0
for each in lbmainlist.get(0,END):
zonelistcount += 1
#print "There are ", zonelistcount, " zones in this experiment."
# major IF processor <complex> (ability to destinguish in multiple zones at once aka platforms within zones)
# rundata [0] = (time,(x,y))
# zonelisttoprocess [('Zone 1', [(158, 169), (118, 248), (154, 268), (191, 188)]), ('Zone 2', [(199, 189), (247, 268), (287, 244), (232, 167), (199, 189)])]
finalstructure = [] # Finalized Data Structure to hold ALL DATA COLLECTED AND PROCESSED, Made up of Trials
#print "\nRUNDATA:", rundata
for trial in rundata: #trial is a list of (time,(xy))
#print "Using this TRIAL in rundata:", trial
finaltrialsdata = [] #List of Zones in this Trial
for zone in zonelisttoprocess: # zone is a tuple of (zonename, listofpolygonpoints)
zoneDPlist = []
#print "For this ZONE in the list to process:", zone
for frame in trial: # frame is a step in the timeline (time,(x,y))
location = frame[1]
zone_polygon = zone[1]
#print "This is the ZONE POlYGON we are checking for points within:", zone_polygon
if isinpolygon(location, zone_polygon) == True:
#print "this one is true!"
atuple = (frame[0], True)
zoneDPlist.append(atuple)
else: #if not in a zone:
#print "false!"
atuple = (frame[0], False)
zoneDPlist.append(atuple)
btuple = (zone[0],zoneDPlist)
finaltrialsdata.append(btuple) #BUGGER
finalstructure.append(finaltrialsdata)
#print "FINAL STRUCTURE:", finalstructure
############################################################################################
#CALCULATE REPORT STATS #Time spent in Each Zone #Time to find Each Zone
#Choices: Correct vs Incorrect
trials_struct = []
report_summary = []
for trial in finalstructure:
for zone_set in trial:
zone_name = zone_set[0]
zone = zone_set[1]
frame1 = zone[0]
time = frame1[0]
marker = frame1[1]
if marker == True:
initial_zone = zone_name
#print "INITAL ZONE:", initial_zone
for trial in finalstructure:
#print "THIS IS THE TRIAL:", trial
#[('Zone 1', [(324.0, False), (648.0, False), (972.0, False), (1296.0, False), (1620.0, False)]), ('Zone 2', [(324.0, False), (648.0, False), (972.0, False), (1296.0, False), (1620.0, False)]), ('Zone 3', [(324.0, False), (648.0, False), (972.0, True), (1296.0, False), (1620.0, False)])]
zone_stats = []
trial_summary = []
last_frame = False
for zone_set in trial:
#('Zone 1', [(324.0, False), (648.0, False), (972.0, False), (1296.0, False), (1620.0, False)])
zone_name = zone_set[0]
zone = zone_set[1]
zonestats = []
#Calculate Trial Time # Inefficient FIX
unpack_trial = zone_set[1]
n = len(unpack_trial)-1
timetuple = unpack_trial[n]
total_trial_time = timetuple[0]
#Calculate Time to Reach the Zone
tfmarker = False
time_to_reach_zone = 0
if zone_name == initial_zone: #if this is the starting zone
itfmarker = True #initial Truth Marker
tfmarker = True
for frame in zone:
this_time = frame[0]
this_frame = frame[1] #True or False
if this_frame == False and itfmarker == True:
itfmarker = False
tfmarker = False
if tfmarker == False:
if this_frame == True:
tfmarker = True
time_to_reach_zone = this_time
else: pass
else:
for frame in zone:
this_time = frame[0]
this_frame = frame[1] #True or False
if tfmarker == False:
if this_frame == True:
tfmarker = True
time_to_reach_zone = this_time
else: pass
#####
#Calculate Number of Entries to Zone
number_of_entries = 0
for frame in zone:
this_frame = frame[1] #True or False
if this_frame == True and last_frame == False:
number_of_entries += 1
else: pass
last_frame = this_frame
#####
#Calculate Total Time Spent in Zone
time_spent_in_zone = 0
last_time_true = 0
for frame in zone:
this_time = frame[0]
this_frame = frame[1] #True or False
if this_frame == True and last_frame == False: #start timing
last_time_true = this_time
elif this_frame == True and last_frame == True: #continue timing
time_spent_in_zone += (this_time - last_time_true)
last_time_true = this_time
else: pass
last_frame = this_frame
#####
#Append Zone Stats to zonestats, then append to zone_stats
zonestats.append(zone_name) #0
zonestats.append(time_to_reach_zone) #1
zonestats.append(number_of_entries) #2
zonestats.append(time_spent_in_zone) #3
zone_stats.append(zonestats)
##Trial Summary - Store in trial_summary[]
#print "ZONE STATS:", zone_stats
#reach_goal? TODO
total_trial_choices = 0
for stat in zone_stats:
total_trial_choices += stat[2]
trial_summary.append(total_trial_time)
trial_summary.append(total_trial_choices)
#Append to Trials_Struct[], zone_stats[] and trial_summary data
build_tuple = (zone_stats, trial_summary)
trials_struct.append(build_tuple)
sum_ccorrectname = vom_lanechoices.get()
sum_cname1 = sum_ccorrectname.split(',')
sum_cname2 = sum_cname1[0]
sum_cname = sum_cname2.strip("')(,")
sum_exitname1 = vom_lanechoices2.get()
sum_cname1 = sum_exitname1.split(',')
sum_cname2 = sum_cname1[0]
sum_exitname = sum_cname2.strip("')(,")
#########################################################################
#########################################################################
#REPORT GENERATION FUNCTIONS
#########################################################################
#Output of results - HTML!
#Prep for output
filename = filename + ".html"
reporttitle = "MTA -" + filename + " at: " #+ str(time.ctime())
reporthead = "Report Sheet:" + filename
#create folder with createPath(path) for images and other info (possible)
dirname = str(filename + "-Report")
global pwd_saves
dir_pwd_saves = pwd_saves + dirname + "/"
savecounter = 0
while path.isdir(dir_pwd_saves) == True:
savecounter += 1
dir_pwd_saves = pwd_saves + dirname + str(savecounter) + "/"
if not path.isdir(dir_pwd_saves):
mkdir(dir_pwd_saves)
print "PWD SAVES", pwd_saves
# Start Output to File
f = file(filename,'w')
htmlfile = filename
newfilename = filename.rsplit(".",1)
filename = newfilename[0]
writebuffer = "<HTML>\n<TITLE>" + reporttitle + "</TITLE>\n"
f.write(writebuffer)
writebuffer = "<h1>" + reporthead + "</h1>\n"
f.write(writebuffer)
#writebuffer = "This file has been auto-generated using the Maze Track Analyzer Program on " #+ str(time.ctime()) + "\n"
#f.write(writebuffer)
f.write("<center><HR>")
writebuffer = "<img src='" + filename + ".jpg'/>\n"
f.write(writebuffer)
im = Image.open(apimageloc)
draw = ImageDraw.Draw(im)
temp = can.create_image(176,144, image = ApImage)
points = []
#print "Redrawing Zone:", lbmainlist
temp_list = list(lbmainlist.get(0, END))
for each in temp_list:
zonedata = each
points = eval(zonedata[1])
textpoint = (points[0], points[1])
draw.text(textpoint, text = zonedata[0], fill ="red")
draw.polygon(points, outline="black")
del draw
jpegsave = str(filename) + ".jpg"
im.save(jpegsave, "JPEG")
newlocation = dir_pwd_saves + jpegsave
shutil.move(jpegsave, newlocation)
############################################################################################
#HTML OUTPUT OF TRIAL DATA
writebuffer = "<H1>Raw Data:</H1>\n"
f.write(writebuffer)
trial_num = 0
runidnum = 0 #for drawing image of run
for trial in trials_struct:
trial_num += 1
zoneinfo = trial[0]
trialsum = trial[1]
#Start Generating Table
run = rodentid[trial_num-1]
writebuffer = "<H1>" + str(rodentid[trial_num-1]) + "</H1>\n"
f.write(writebuffer)
writebuffer = '<table border="1"> \n <tr>' #Start of table
f.write(writebuffer)
writebuffer = "<img src='" + run + ".jpg' ALIGN='right'/>"
f.write(writebuffer)
#Column Headings
f.write("<td>Zone:</td>")
f.write("<td><B>Time to Reach (s)</B></td>")
f.write("<td><B>Entries</B></td>")
f.write("<td><B>Time Spent (s)</B></td></tr>")
total_choices = 0
for zone in zoneinfo:
f.write("<tr>") #Start New Row
writebuffer = "<td><b>" + str(zone[0]) + "</b></td>" #Zone Name
f.write(writebuffer)
writebuffer = "<td><center>" + str(zone[1]/float(1000)) + "</center></td>" #Time to Reach
f.write(writebuffer)
if zone[0] == initial_zone:
writebuffer = "<td><center>" + str(zone[2]-1) + "</center></td>" #Entries
f.write(writebuffer)
else:
writebuffer = "<td><center>" + str(zone[2]) + "</center></td>" #Entries
f.write(writebuffer)
writebuffer = "<td><center>" + str(zone[3]/float(1000)) + "</center></td>" #Timespent
f.write(writebuffer)
if zone[0] == sum_cname: #IF THIS IS CORRECT ZONE
sum_ccorrect[run] = zone[2]
if zone[0] == sum_exitname: #IF THIS IS EXIT
sum_duration[run] = (zone[1]/float(1000))
if zone[2] > 0:
sum_reachgoal[run] = 1
else:
sum_reachgoal[run] = 0
if zone[0] == initial_zone:
total_choices += zone[2]-1 #remove extra entry due to starting zone
else:
total_choices += zone[2]
if sum_duration[run] == 0: #if rodent does not find exit, make duration 60 seconds
sum_duration[run] = 60
f.write("</tr></table>\n")
create_runimage(runidnum, run, dir_pwd_saves)
sum_cwrong[run] = (total_choices - sum_ccorrect[run] - sum_reachgoal[run]) #wrong choices is equal to the total - correct - exit
runidnum += 1 #advance for next run
#HTML OUTPUT OF RUN SUMMARY
f.write("\n<H1>Run(s) Summary </H1>\n")
writebuffer = '<table border="1"> \n <tr>' #Start of table
f.write(writebuffer)
#Column Headings
f.write("<td>Run(s) #</td>")
f.write("<td><B>Duration (s)</B></td>")
f.write("<td><B>Reach Goal (1/0)</B></td>")
f.write("<td><B>Choice Correct</B></td>")
f.write("<td><B>Choice Wrong</B></td>")
f.write("<td><B>Correct (%)</B></td>")
f.write("<td><B>Distance Traveled (cm)</B></td></tr>")
f.write("<tr>") #Start New Row
total_disp = 0
total_correct = 0
total_wrong = 0
total_duration = 0
total_reached = 0