Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

newdata.py 41 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
  1. ##
  2. '''Make sure the following directories are found by python:
  3. #sys.path.append('/home/michael/code/mousemaze')
  4. #sys.path.append('/home/michael/src/pyControl/tools')
  5. This is currently being done through $PYTHONPATH set by the conda scripts
  6. '''
  7. import numpy as np
  8. import pylab as pl
  9. import matplotlib.pyplot as plt
  10. import glob
  11. import h5py
  12. import copy
  13. import os
  14. import sys
  15. import mazex as mx
  16. from mazex.exceptions import AlgorithmFail
  17. import rsync
  18. import tqdm
  19. import numba
  20. import itertools
  21. import seaborn as sns
  22. import ray
  23. from joblib import Memory
  24. location = './cachedir'
  25. memory = Memory(location)
  26. import diskcache
  27. cache = diskcache.Cache('./cachedir')
  28. from SALib.sample import saltelli
  29. from scipy.optimize import minimize
  30. import pandas as pd
  31. ##
  32. def maze_for_session(mouse, year, month, day):
  33. """Returns the appropriate maze object.
  34. """
  35. fully_connected_maze = mx.RandomButConnectedSquareMaze(6, 6*5*2)
  36. original_maze = mx.SquareMaze(6)
  37. h_connections = [[(0,0), (1,0)], [(1,0), (2,0)], [(2,0), (3,0)], [(3,0), (4,0)],
  38. [(3,1), (4,1)],
  39. [(0,2), (1,2)], [(2,2), (3,2)], [(3,2), (4,2)], [(4,2), (5,2)],
  40. [(1,3), (2,3)], [(3,3), (4,3)],
  41. [(0,4), (1,4)], [(2,4), (3,4)], [(3,4), (4,4)], [(4,4), (5,4)],
  42. [(0,5), (1,5)], [(1,5), (2,5)], [(2,5), (3,5)], [(4,5), (5,5)]]
  43. v_connections = [[(0,0), (0,1)], [(0,1), (0,2)], [(0,3), (0,4)], [(0,4), (0,5)],
  44. [(1,1), (1,2)], [(1,2), (1,3)], [(1,3), (1,4)],
  45. [(2,0), (2,1)], [(2,2), (2,3)], [(2,3), (2,4)], [(2,4), (2,5)],
  46. [(3,0), (3,1)], [(3,3), (3,4)],
  47. [(4,1), (4,2)], [(4,2), (4,3)], [(4,4), (4,5)],
  48. [(5,0), (5,1)], [(5,1), (5,2)], [(5,2), (5,3)], [(5,3), (5,4)]]
  49. original_maze.add_edges_from(h_connections)
  50. original_maze.add_edges_from(v_connections)
  51. maze1_str = '''
  52. ._._._._._.
  53. | . |_._|_|
  54. |_| | |_|_.
  55. |_| ._. ._.
  56. |_| . | |_|
  57. |_._|_|_|_|
  58. '''
  59. maze2_mod_str = '''
  60. ._._._._. .
  61. ._._| ._|_|
  62. |_. | | |_.
  63. | . |_|_._|
  64. | |_. ._|_.
  65. |_|_|_|_. |
  66. '''
  67. maze2_str = '''
  68. ._._._._. .
  69. |_._| ._|_|
  70. |_. | | |_.
  71. | . |_|_._|
  72. | |_. ._._|
  73. |_|_._|_._|
  74. '''
  75. maze1 = mx.mazes.maze_from_ASCII(maze1_str)
  76. maze2_mod = mx.mazes.maze_from_ASCII(maze2_mod_str)
  77. maze2 = mx.mazes.maze_from_ASCII(maze2_str)
  78. if int(year) == 2019:
  79. if int(month) == 8:
  80. if int(day) >= 8 and int(day) <= 17:
  81. # fully connected maze
  82. maze = fully_connected_maze
  83. elif int(day) >= 19 and int(day) <= 28:
  84. maze = original_maze
  85. elif int(day) >= 30 and int(day) <= 31:
  86. maze = maze1
  87. elif int(month) == 9:
  88. if int(day) >= 1 and int(day) <= 10:
  89. maze = maze1
  90. elif int(day) == 12:
  91. if mouse == '10I' or mouse == '10II':
  92. maze = maze2_mod
  93. else:
  94. maze = maze2
  95. elif int(day) >= 13 and int(day) <= 21:
  96. maze = maze2
  97. return maze
  98. maze_names = ['fully','original','maze1','maze2']
  99. ##
  100. #------------------------------------ Parameters -----------------------------
  101. mice = ['10I', '10II', '10III', '11I', '11II', '12I', '12II', '12III']
  102. experiment_days = {'fully': [
  103. ['2019', '08', '08'],
  104. ['2019', '08', '09'],
  105. ['2019', '08', '10'],
  106. ['2019', '08', '11'],
  107. ['2019', '08', '12'],
  108. ['2019', '08', '13'],
  109. ['2019', '08', '14'],
  110. ['2019', '08', '15'],
  111. ['2019', '08', '16'],
  112. ['2019', '08', '17']
  113. ],
  114. 'original': [
  115. ['2019', '08', '19'],
  116. ['2019', '08', '20'],
  117. ['2019', '08', '21'],
  118. ['2019', '08', '22'],
  119. ['2019', '08', '23'],
  120. ['2019', '08', '24'],
  121. ['2019', '08', '25'],
  122. ['2019', '08', '26'],
  123. ['2019', '08', '27'],
  124. ['2019', '08', '28']
  125. ],
  126. 'maze1': [
  127. ['2019', '08', '30'],
  128. ['2019', '08', '31'],
  129. ['2019', '09', '01'],
  130. ['2019', '09', '02'],
  131. ['2019', '09', '03'],
  132. ['2019', '09', '04'],
  133. ['2019', '09', '05'],
  134. ['2019', '09', '06'],
  135. ['2019', '09', '07'],
  136. ['2019', '09', '08'],
  137. ['2019', '09', '09'],
  138. ['2019', '09', '10']
  139. ],
  140. 'maze2': [
  141. ['2019', '09', '12'],
  142. ['2019', '09', '13'],
  143. ['2019', '09', '14'],
  144. ['2019', '09', '15'],
  145. ['2019', '09', '16'],
  146. ['2019', '09', '17'],
  147. ['2019', '09', '18'],
  148. ['2019', '09', '19'],
  149. ['2019', '09', '20'],
  150. ['2019', '09', '21']
  151. ]
  152. }
  153. fully_connected_maze = mx.RandomButConnectedSquareMaze(6, 6*5*2)
  154. maze = fully_connected_maze
  155. skip_first_and_last_trials = True
  156. fps = 60
  157. background_file = '/home/michael/code/mousemaze/figures/stills/background_2019.svg'
  158. background_PNG = '/home/michael/code/mousemaze/figures/stills/still_2019.png'
  159. arduino_data_folder = '/mnt/dataz/michael/git-annex/client/data/data/interim/bigmaze/2019/pokestr_fixed'
  160. dlc_data_folder = '/mnt/dataz/michael/git-annex/client/data/data/processed/bigmaze/2019/deeplabcut/resnet50-it103'
  161. bonsai_metadata_folder = '/mnt/dataz/michael/git-annex/client/data/data/interim/bigmaze/2019/video_metadata'
  162. ##
  163. #---------------------------------Parsing CV data-----------------------------
  164. """Now we extract the regions corresponding to the different pokes on the
  165. image using the annotated SVG file.
  166. """
  167. region_mapping = mx.data.regionmapping.RegionMapping(background_file, background_PNG)
  168. step_count = 0
  169. trial_count = 0
  170. session_count = 0
  171. discarded_trials_has_slow_step = 0
  172. discarded_trials_neg_duration = 0
  173. discarded_trials_not_consumed = 0
  174. discarded_trials_alignment=0
  175. discarded_steps_too_slow = 0
  176. discarded_trials_empty = 0
  177. shortened_trials = 0
  178. n_shortenings = 0
  179. inter_port_intervals = []
  180. sessions = [] # all sessions separated by day an mouse
  181. super_sessions = {} # for each mouse all trials together in chronological order
  182. mega_session = mx.Session()
  183. session_durations = {}
  184. sessions_no_trials = 0
  185. min_trial_duration = 1000 #ms
  186. #step_duration_threshold = 5500 #ms
  187. step_duration_threshold = 700000 #ms
  188. jitter_tolerance = 2000 #ms
  189. discard_whole_trials = True # If True, then trials with long steps will not be trimmed but entirely discarded
  190. max_trial_duration = 10000000
  191. day_sessions = {}
  192. #@numba.jit(parallel=True)
  193. #for d in tqdm.tqdm(experiment_days[:]):#sessions_by_day:
  194. ##
  195. #@ray.remote
  196. #@cache.memoize()
  197. #@memory.cache
  198. def get_session(mouse, date):
  199. '''Build Session object with data for that mouse and experiment_day
  200. '''
  201. #TODO: turn region_mapping into a function argument
  202. background_file = '/home/michael/code/mousemaze/figures/stills/background_2019.svg'
  203. background_PNG = '/home/michael/code/mousemaze/figures/stills/still_2019.png'
  204. region_mapping = mx.data.regionmapping.RegionMapping(background_file, background_PNG)
  205. arduino_data_folder = '/mnt/dataz/michael/git-annex/client/data/data/interim/bigmaze/2019/pokestr_fixed'
  206. dlc_data_folder = '/mnt/dataz/michael/git-annex/client/data/data/processed/bigmaze/2019/deeplabcut/resnet50-it103'
  207. bonsai_metadata_folder = '/mnt/dataz/michael/git-annex/client/data/data/interim/bigmaze/2019/video_metadata'
  208. # FIXME: turn these into arguments
  209. min_trial_duration = 1000 #ms
  210. step_duration_threshold = 700000 #ms
  211. jitter_tolerance = 2000 #ms
  212. discard_whole_trials = True # If True, then trials with long steps will not be trimmed but entirely discarded
  213. max_trial_duration = 10000000
  214. session_step_count = 0
  215. n_shortenings = 0
  216. discarded_steps_too_slow = 0
  217. shortened_trials = 0
  218. discarded_trials_has_slow_step = 0
  219. discarded_trials_empty = 0
  220. discarded_trials_neg_duration = 0
  221. discarded_trials_not_consumed = 0
  222. maze = maze_for_session(mouse, *date)
  223. #FIXME: this only analysis the first file found; there can be several for a single session when problems occur
  224. ddd = '{}{}{}'.format(*date)
  225. arduino_file_paths = glob.glob(os.path.join(arduino_data_folder, mouse+'_'+ddd+'**.txt'), recursive=True)
  226. if len(arduino_file_paths) != 1:
  227. raise Exception('There are more or less than exactly one arduino data file for mouse {} and date {}'.format(mouse, date))
  228. else:
  229. arduino_file_path = arduino_file_paths[0]
  230. arduino_data = mx.data.arduino.ArduinoDataFile(arduino_file_path)
  231. d_d_d = '{}-{}-{}'.format(*date)
  232. bonsai_metadata_file_paths = glob.glob(os.path.join(bonsai_metadata_folder, 'metadata_'+mouse+'_'+d_d_d+'**.csv'), recursive=True)
  233. dlc_coords_file_paths = glob.glob(os.path.join(dlc_data_folder, mouse+'_'+d_d_d+'**.h5'), recursive=True)
  234. if len(bonsai_metadata_file_paths) != 1:
  235. raise Exception('There are more or less than exactly one bonsai metadata file for mouse {} and date {}'.format(mouse, date))
  236. else:
  237. bonsai_metadata_file_path = bonsai_metadata_file_paths[0]
  238. if len(dlc_coords_file_paths) != 1:
  239. raise Exception('There are more or less than exactly one Deeplabcut results file for mouse {} and date {}'.format(mouse, date))
  240. else:
  241. dlc_coords_file_path = dlc_coords_file_paths[0]
  242. # FIXME: this should eventually be addressed
  243. # There was a problem with the data acquisition and this should be
  244. # skipped
  245. #try:
  246. bonsai_data = mx.data.bonsai.BonsaiData(
  247. dlc_coords_file_path, bonsai_metadata_file_path,
  248. metadata_delimiter=',', fps=60, background_file=background_file,
  249. background_PNG=background_PNG, maze=maze, frame_number_column=0,
  250. timestamps_column=1, sync_column=2, hardware_timestamps=True)
  251. #except ValueError:
  252. #continue
  253. aligner = rsync.Rsync_aligner(
  254. arduino_data.syncon_event_times.ravel().astype('int'),
  255. bonsai_data.syncon_event_times.ravel().astype('int')[0:arduino_data.syncon_event_times.size],
  256. chunk_size=5, plot=True)
  257. goals = [region_mapping.address_to_coord_dic[poke_address] for poke_address in arduino_data.reward_events[:,1]]
  258. session = mx.Session(date=ddd, subject=mouse)
  259. #iterate over trials
  260. trial_count = 0
  261. for i, tgoal in enumerate(zip(arduino_data.reward_event_times[1:-1], goals[1:-1])):
  262. #counters
  263. trial_count += 1
  264. shortened = False
  265. # we get the time of reward and the current goal but to reconstruct trajectory we need to look 'backward'
  266. t_arduino_arrival_goal, goal = tgoal
  267. previous_goal = goals[i] #this does correspond to previous goal as we start iteration over second element of goals
  268. previous_goal_t = arduino_data.reward_event_times[i]
  269. trial = mx.Trial(maze, goal, delay_period = arduino_data.delay_period)
  270. trial_begin_t_video = aligner.A_to_B(previous_goal_t + arduino_data.delay_period)
  271. trial_end_t_video = aligner.A_to_B(t_arduino_arrival_goal)
  272. port_visit_times_video, visited_ports = bonsai_data.get_trajectory(trial_begin_t_video, trial_end_t_video, maze)
  273. # FIXME: for a reason we don't yet understand sometimes the list of
  274. # visited_ports is empty. I suspect it is the case for trials where
  275. # reward is adjacent or the centroid gets lost. Needs investigation
  276. # and removal of this catch if
  277. if len(visited_ports) == 0:
  278. continue
  279. # now we convert the time at which visits to a port are detected
  280. # back to Arduino time
  281. port_visit_times_arduino = aligner.B_to_A(port_visit_times_video)
  282. # FIXME: there could be a discrepancy between port_visit_times[0]
  283. # and the t_start we are using here: previous_goal_t +
  284. # arduino_data.delay_period
  285. #
  286. # FIXME:
  287. initial_step = mx.Step(loc=visited_ports[0], trial=trial, time=previous_goal_t + arduino_data.delay_period)
  288. trial.steps.append(initial_step)
  289. #iterate over steps
  290. for t_arrival_at_port, loc in zip(port_visit_times_arduino[1:], visited_ports[1:]):
  291. session_step_count += 1
  292. #TODO: reorganize these messy ifs
  293. if (t_arrival_at_port - trial.steps[-1].time) < step_duration_threshold:
  294. # Step duration less than the threshold
  295. step = mx.Step(loc, trial, previous=trial.steps[-1], time=t_arrival_at_port)
  296. trial.steps.append(step)
  297. else:
  298. # The animal spent more than the threshold time at a given port
  299. if trial.steps[-1].loc != previous_goal:
  300. #only discard if this was not the first step. They are allowed to spend longer at the previous port drinking
  301. if not discard_whole_trials:
  302. trial.shortened = True #used to count trials that were shortened
  303. n_shortenings += 1
  304. discarded_steps_too_slow += len(trial.steps)
  305. trial.steps = []
  306. initial_step = mx.Step(loc=loc, trial=trial, time=t_arrival_at_port)
  307. trial.steps.append(initial_step)
  308. else:
  309. #the whole trial is discarded
  310. discarded_trials_has_slow_step += 1
  311. break
  312. else:
  313. #it's the first step so it still gets included as normal
  314. step = mx.Step(loc, trial, previous = trial.steps[-1], time=t_arrival_at_port)
  315. trial.steps.append(step)
  316. if loc == goal:
  317. # the animal is at the reward port
  318. # now we need to check that he actually poked and got the reward:
  319. trial.steps[-1].time = copy.deepcopy(t_arduino_arrival_goal)
  320. if np.abs(t_arduino_arrival_goal - t_arrival_at_port) < jitter_tolerance:
  321. trial.steps[-1].time = t_arduino_arrival_goal # for the last step we use the arduino time 'cause it is more accurate
  322. if min_trial_duration <= trial.duration <= max_trial_duration:
  323. if trial.shortened:
  324. shortened_trials += 1
  325. if len(trial.steps) >= 3:
  326. #discard empty trials where all previous steps to goal were discarded
  327. session.trials.append(trial)
  328. else:
  329. discarded_trials_empty += 1
  330. else:
  331. discarded_trials_neg_duration += 1
  332. else:
  333. #the animal didn't consume reward or there is another more exotic problem
  334. discarded_trials_not_consumed += 1
  335. break
  336. return session
  337. ##
  338. def try_get_session(mouse, date):
  339. try:
  340. session = get_session(mouse, date)
  341. return session
  342. except:
  343. return None
  344. @cache.memoize()
  345. def get_all_sessions(mice, experiment_days):
  346. ray.init(ignore_reinit_error=True)
  347. sessions = {}
  348. for maze in experiment_days.keys():
  349. iterable_inputs = list(itertools.product(mice, experiment_days[maze]))
  350. # FIXME: remove this ugly hack!
  351. get_session_remote = ray.remote(try_get_session)
  352. futures = [get_session_remote.remote(mouse=md[0], date=md[1]) for md in iterable_inputs]
  353. sessions[maze] = ray.get(futures)
  354. return sessions
  355. ##
  356. sessions = get_all_sessions(mice, experiment_days)
  357. ##
  358. #sessions_bak = copy.deepcopy(sessions)
  359. #sessions = sessions.func
  360. ##
  361. ## Using joblib
  362. #from joblib import Parallel, delayed
  363. #rj = Parallel(n_jobs=24, verbose=10)(delayed(get_session)(md[0], md[1]) for md in iterable_inputs)
  364. ##
  365. ##
  366. # WIP: "arrows" plots
  367. for maze in list(experiment_days.keys())[1:]:
  368. prob_plan[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  369. prob_vec[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  370. experiment_days_strs = []
  371. for d in experiment_days[maze]:
  372. experiment_days_strs.append(d[0]+d[1]+d[2])
  373. for s in sessions[maze]:
  374. if s:
  375. # this block will only be executed on valid session objects
  376. day_index = experiment_days_strs.index(s.date)
  377. mouse_index = mice.index(s.subject)
  378. else:
  379. # there was a problem with the datafiles and we haven't retrieved the session
  380. print('Passing')
  381. pass
  382. ##
  383. # Excess steps analysis
  384. sessions_steps = pd.DataFrame(columns=['maze', 'exp_day', 'run_day', 'mouse', 'esteps', 'ntrials', 'esteps_per_trial'])
  385. excess_steps = {}
  386. n_trials = {}
  387. excess_steps_per_trial = {}
  388. max_y_lim = 0
  389. for maze in experiment_days.keys():
  390. excess_steps[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  391. n_trials[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  392. experiment_days_strs = []
  393. for d in experiment_days[maze]:
  394. experiment_days_strs.append(d[0]+d[1]+d[2])
  395. for s in sessions[maze]:
  396. if s:
  397. # this block will only be executed on valid session objects
  398. day_index = experiment_days_strs.index(s.date)
  399. mouse_index = mice.index(s.subject)
  400. excess_steps[maze][day_index, mouse_index] = s.count_excess_steps()
  401. n_trials[maze][day_index, mouse_index] = len(s.trials)
  402. excess_steps_per_trial[maze] = excess_steps[maze]/n_trials[maze]
  403. if maze == 'fully':
  404. run_day = day_index+1
  405. elif maze == 'original':
  406. run_day = day_index+12
  407. elif maze == 'maze1':
  408. run_day = day_index+23
  409. elif maze == 'maze2':
  410. run_day = day_index+36
  411. sessions_steps = sessions_steps.append({
  412. 'maze':maze, 'exp_day':day_index+1, 'run_day': run_day,
  413. 'mouse':s.subject,
  414. 'esteps': s.count_excess_steps(), 'ntrials': len(s.trials),
  415. 'esteps_per_trial': s.count_excess_steps()/len(s.trials)},
  416. ignore_index=True)
  417. else:
  418. # there was a problem with the datafiles and we haven't retrieved the session
  419. print('Passing')
  420. pass
  421. plt.figure()
  422. sns.violinplot(data=excess_steps_per_trial[maze].T, inner='box', cut=0, color=sns.color_palette()[1])
  423. _, max_y = pl.ylim()
  424. if max_y > max_y_lim:
  425. max_y_lim = max_y
  426. for x in range(len(experiment_days.keys())):
  427. #pl.close()
  428. pass
  429. ##
  430. # All excess steps for all topologies on the same plot
  431. plt.figure()
  432. ax = plt.gca()
  433. discriminability = ['0', '0.05', '0.09', '0.18']
  434. maze_names = ['fully', 'original', 'maze2', 'maze1']
  435. for maze, d in zip(maze_names, discriminability):
  436. sem = sessions_steps[sessions_steps['maze']==maze].groupby('exp_day')['esteps_per_trial'].sem()
  437. std = sessions_steps[sessions_steps['maze']==maze].groupby('exp_day')['esteps_per_trial'].std()
  438. #sessions_steps[sessions_steps['maze']==maze].groupby('exp_day').mean().plot(y='esteps_per_trial', label=maze, yerr=sem, ax=ax, kind='line')
  439. sessions_steps[sessions_steps['maze']==maze].groupby('exp_day').mean().plot(y='esteps_per_trial', label=d, yerr=sem, ax=ax, kind='line')
  440. plt.xlabel('Experiment day')
  441. plt.ylabel('Avg. Excess steps / trial')
  442. plt.xlim(0.5,12.5)
  443. plt.xticks(list(range(1,13)))
  444. plt.ylim(0, 10)
  445. plt.legend(title='Informative states')
  446. ##
  447. # All excess steps for all topologies side by side
  448. plt.figure()
  449. ax = plt.gca()
  450. discriminability = ['0', '0.05', '0.09', '0.18']
  451. maze_names = ['fully', 'original', 'maze2', 'maze1']
  452. for maze, d in zip(maze_names, discriminability):
  453. sem = sessions_steps[sessions_steps['maze']==maze].groupby('run_day')['esteps_per_trial'].sem()
  454. std = sessions_steps[sessions_steps['maze']==maze].groupby('run_day')['esteps_per_trial'].std()
  455. #sessions_steps[sessions_steps['maze']==maze].groupby('exp_day').mean().plot(y='esteps_per_trial', label=maze, yerr=sem, ax=ax, kind='line')
  456. if maze == 'fully':
  457. x = list(range(1, 11))
  458. elif maze == 'original':
  459. x = list(range(12, 22))
  460. elif maze == 'maze1':
  461. x = list(range(23, 35))
  462. elif maze == 'maze2':
  463. x = list(range(36, 46))
  464. sessions_steps[sessions_steps['maze']==maze].groupby('run_day').mean().plot(y='esteps_per_trial', label=d, yerr=std, ax=ax, kind='line')
  465. plt.xlabel('Experiment day')
  466. plt.ylabel('Avg. Excess steps / trial (+/- STD)')
  467. #plt.xlim(0.5,12.5)
  468. #plt.xticks(list(range(1,13)))
  469. #plt.ylim(0, 10)
  470. plt.legend(title='Fraction informative states')
  471. ##
  472. # All excess Euclidean distances per step for all topologies side by side
  473. plt.figure()
  474. ax = plt.gca()
  475. discriminability = ['0', '0.05', '0.09', '0.18']
  476. maze_names = ['fully', 'original', 'maze2', 'maze1']
  477. for maze, d in zip(maze_names, discriminability):
  478. sem = sessions_steps[sessions_steps['maze']==maze].groupby('run_day')['esteps_per_trial'].sem()
  479. std = sessions_steps[sessions_steps['maze']==maze].groupby('run_day')['esteps_per_trial'].std()
  480. #sessions_steps[sessions_steps['maze']==maze].groupby('exp_day').mean().plot(y='esteps_per_trial', label=maze, yerr=sem, ax=ax, kind='line')
  481. if maze == 'fully':
  482. x = list(range(1, 11))
  483. elif maze == 'original':
  484. x = list(range(12, 22))
  485. elif maze == 'maze1':
  486. x = list(range(23, 35))
  487. elif maze == 'maze2':
  488. x = list(range(36, 46))
  489. sessions_steps[sessions_steps['maze']==maze].groupby('run_day').mean().plot(y='esteps_per_trial', label=d, yerr=std, ax=ax, kind='line')
  490. plt.xlabel('Experiment day')
  491. plt.ylabel('Avg. Excess steps / trial (+/- STD)')
  492. #plt.xlim(0.5,12.5)
  493. #plt.xticks(list(range(1,13)))
  494. #plt.ylim(0, 10)
  495. plt.legend(title='Fraction informative states')
  496. ##
  497. for maze in experiment_days.keys():
  498. pl.figure()
  499. sns.violinplot(data=excess_steps_per_trial[maze].T, inner='box', color=sns.color_palette()[1])
  500. #plt.xticks(range(len(experiment_days[maze])), labels=range(1, len(experiment_days[maze])+1))
  501. pl.xlabel('Experiment day on maze')
  502. pl.ylabel('Avg. excess steps/trial')
  503. pl.title('{}'.format(maze))
  504. pl.ylim([0, max_y_lim])
  505. pl.show()
  506. pl.show()
  507. ##
  508. # Excess steps per trial analysis
  509. n_trials = {}
  510. excess_steps_per_trial = {}
  511. max_y_lim = 0
  512. for maze in experiment_days.keys():
  513. max_trials = np.max([len(s.trials) for s in sessions[maze] if s])
  514. excess_steps_per_trial[maze] = np.full([len(experiment_days[maze]), len(mice), max_trials], np.nan)
  515. experiment_days_strs = []
  516. for d in experiment_days[maze]:
  517. experiment_days_strs.append(d[0]+d[1]+d[2])
  518. for s in sessions[maze]:
  519. if s:
  520. # this block will only be executed on valid session objects
  521. day_index = experiment_days_strs.index(s.date)
  522. mouse_index = mice.index(s.subject)
  523. excess_steps_mouse_session_trial = [t.excess_steps() for t in s.trials]
  524. excess_steps_per_trial[maze][day_index, mouse_index, 0:len(excess_steps_mouse_session_trial)] = excess_steps_mouse_session_trial
  525. else:
  526. # there was a problem with the datafiles and we haven't retrieved the session
  527. print('Passing')
  528. pass
  529. ##
  530. for maze in experiment_days.keys():
  531. for di in [0, 9]:
  532. pl.figure()
  533. pl.plot(excess_steps_per_trial[maze][di,:,:].T)
  534. pl.xlabel('trial #')
  535. pl.ylabel('excess steps')
  536. pl.title('Maze: {} day: {}'.format(maze, di+1))
  537. pl.show()
  538. ## Excess Euclidean Distance per step
  539. n_trials = {}
  540. excess_steps_per_trial = {}
  541. max_y_lim = 0
  542. for maze in experiment_days.keys():
  543. max_trials = np.max([len(s.trials) for s in sessions[maze] if s])
  544. excess_steps_per_trial[maze] = np.full([len(experiment_days[maze]), len(mice), max_trials], np.nan)
  545. experiment_days_strs = []
  546. for d in experiment_days[maze]:
  547. experiment_days_strs.append(d[0]+d[1]+d[2])
  548. for s in sessions[maze]:
  549. if s:
  550. # this block will only be executed on valid session objects
  551. day_index = experiment_days_strs.index(s.date)
  552. mouse_index = mice.index(s.subject)
  553. excess_steps_mouse_session_trial = [t.excess_steps() for t in s.trials]
  554. excess_steps_per_trial[maze][day_index, mouse_index, 0:len(excess_steps_mouse_session_trial)] = excess_steps_mouse_session_trial
  555. else:
  556. # there was a problem with the datafiles and we haven't retrieved the session
  557. print('Passing')
  558. pass
  559. ##
  560. for maze in experiment_days.keys():
  561. for di in [0, 9]:
  562. pl.figure()
  563. pl.plot(excess_steps_per_trial[maze][di,:,:].T)
  564. pl.xlabel('trial #')
  565. pl.ylabel('excess steps')
  566. pl.title('Maze: {} day: {}'.format(maze, di+1))
  567. pl.show()
  568. ##
  569. # Planning epochs raster
  570. n_trials = {}
  571. planning_steps = {}
  572. max_y_lim = 0
  573. for maze in experiment_days.keys():
  574. max_steps = np.max([s.count_total_steps() for s in sessions[maze] if s])
  575. planning_steps[maze] = np.full([len(experiment_days[maze]), len(mice), max_steps], np.nan)
  576. experiment_days_strs = []
  577. for d in experiment_days[maze]:
  578. experiment_days_strs.append(d[0]+d[1]+d[2])
  579. for s in sessions[maze]:
  580. if s:
  581. maze_obj = s.maze
  582. # this block will only be executed on valid session objects
  583. day_index = experiment_days_strs.index(s.date)
  584. mouse_index = mice.index(s.subject)
  585. session_no_last_steps = [step for step in s.steps() if step.subsequent]
  586. orthogonal_steps = mx.analysis.iterators.orthogonal_planning_vectornav(session_no_last_steps, maze_obj)
  587. for i, s in enumerate(orthogonal_steps):
  588. if s.subsequent:
  589. # we are excluding the last step
  590. if maze_obj.distances_dictionary[s.subsequent.loc][s.trial.goal] < maze_obj.distances_dictionary[s.loc][s.trial.goal]:
  591. # it is a planning epoch
  592. planning_steps[maze][day_index, mouse_index, i] = 1
  593. else:
  594. planning_steps[maze][day_index, mouse_index, i] = 0
  595. else:
  596. # there was a problem with the datafiles and we haven't retrieved the session
  597. print('Passing: {}\t{}'.format(maze, mouse_index))
  598. pass
  599. ##
  600. for maze in experiment_days.keys():
  601. for di in [0, 9]:
  602. pl.figure()
  603. pl.plot(excess_steps_per_trial[maze][di,:,:].T)
  604. pl.xlabel('trial #')
  605. pl.ylabel('excess steps')
  606. pl.title('Maze: {} day: {}'.format(maze, di+1))
  607. pl.show()
  608. ##
  609. sns.violinplot(data=excess_steps_per_trial[maze].T, inner='box', cut=0, color=sns.color_palette()[1])
  610. _, max_y = pl.ylim()
  611. if max_y > max_y_lim:
  612. max_y_lim = max_y
  613. for x in range(len(experiment_days.keys())):
  614. pl.close()
  615. ##
  616. for maze in experiment_days.keys():
  617. pl.figure()
  618. sns.violinplot(data=excess_steps_per_trial[maze].T, inner='box', color=sns.color_palette()[1])
  619. pl.xticks(range(len(experiment_days[maze])), labels=range(1, len(experiment_days[maze])+1))
  620. pl.xlabel('Experiment day on maze')
  621. pl.ylabel('Avg. excess steps/trial')
  622. pl.title('{}'.format(maze))
  623. pl.ylim([0, max_y_lim])
  624. pl.show()
  625. pl.show()
  626. ##
  627. # Orthogonal choice probability
  628. fig = plt.figure()
  629. prob_plan = {}
  630. prob_vec = {}
  631. for maze in ['original', 'maze2', 'maze1']:
  632. #for maze in list(experiment_days.keys())[1:]:
  633. prob_plan[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  634. prob_vec[maze] = np.full([len(experiment_days[maze]), len(mice)], np.nan)
  635. experiment_days_strs = []
  636. for d in experiment_days[maze]:
  637. experiment_days_strs.append(d[0]+d[1]+d[2])
  638. for s in sessions[maze]:
  639. if s:
  640. # this block will only be executed on valid session objects
  641. day_index = experiment_days_strs.index(s.date)
  642. mouse_index = mice.index(s.subject)
  643. #orthogonal_steps_gen = mx.analysis.iterators.first_exit_over_steps(mx.analysis.iterators.orthogonal_planning_vectornav(s.steps(), s.maze, distance='manhattan', discard_backtracked=True, either_plan_or_nav=True))
  644. #orthogonal_steps_gen = mx.analysis.iterators.first_exit_over_steps(mx.analysis.iterators.orthogonal_planning_vectornav(mx.analysis.iterators.exclude_goal(s.steps()), s.maze, distance='euclidian'))
  645. orthogonal_steps_gen = mx.analysis.iterators.first_exit_over_steps(mx.analysis.iterators.orthogonal_planning_vectornav(mx.analysis.iterators.exclude_goal(s.steps()), s.maze, distance='manhattan'))
  646. # orthogonal_steps_gen = mx.analysis.iterators.exclude_goal(s.steps())
  647. prob_plan[maze][day_index, mouse_index], prob_vec[maze][day_index, mouse_index] = mx.analysis.probs.prob_plan_prob_vec(orthogonal_steps_gen, subtract_random=False, spatial_distance='manhattan')
  648. else:
  649. # there was a problem with the datafiles and we haven't retrieved the session
  650. print('Passing')
  651. pass
  652. pl.figure()
  653. sns.violinplot(data=prob_plan[maze].T, inner='box', color=sns.color_palette()[1])
  654. #pl.xticks(range(len(experiment_days[maze])), labels=range(1, len(experiment_days[maze])+1))
  655. pl.xlabel('Experiment day on maze')
  656. pl.ylabel('p(choice = optimal)')
  657. pl.title('{}'.format(maze))
  658. pl.ylim([0, 1])
  659. plt.figure(fig.number)
  660. plt.plot(np.nanmedian(prob_plan[maze].T, axis=0), label=maze)
  661. pl.figure()
  662. sns.violinplot(data=prob_vec[maze].T, inner='box', color=sns.color_palette()[1])
  663. #pl.xticks(range(len(experiment_days[maze])), labels=range(1, len(experiment_days[maze])+1))
  664. pl.xlabel('Experiment day on maze')
  665. pl.ylabel('p(choice = optimal)')
  666. pl.title('{}'.format(maze))
  667. pl.ylim([0, 1])
  668. plt.legend()
  669. plt.figure(fig.number)
  670. plt.xlabel("Experiment day")
  671. plt.ylabel("Fraction of optimal choices when \n orthogonal (median across mice)")
  672. plt.legend()
  673. pl.show()
  674. ##
  675. # Vector plot
  676. ses = sessions['maze1'][-1]
  677. mx.analysis.probs.arrows_plot([ses], maze=ses.maze)
  678. ##
  679. early_sessions_maze1 = [s for s in sessions['maze1'] if (s is not None) and (s.date=='20190830')]
  680. late_sessions_maze1 = [s for s in sessions['maze1'] if (s is not None) and (s.date=='20190910')]
  681. maze1 = early_sessions_maze1[0].maze
  682. ##
  683. mx.analysis.probs.arrows_plot2(early_sessions_maze1, maze=maze1)
  684. mx.analysis.probs.arrows_plot2(late_sessions_maze1, maze=maze1)
  685. ##
  686. early_sessions_maze2 = [s for s in sessions['maze2'] if (s is not None) and (s.date=='20190912')]
  687. late_sessions_maze2 = [s for s in sessions['maze2'] if (s is not None) and (s.date=='20190921')]
  688. maze2 = early_sessions_maze2[0].maze
  689. mx.analysis.probs.arrows_plot2(early_sessions_maze2, maze=maze2)
  690. mx.analysis.probs.arrows_plot2(late_sessions_maze2, maze=maze2)
  691. ##
  692. early_sessions_orig = [s for s in sessions['original'] if (s is not None) and (s.date=='20190819')]
  693. late_sessions_orig = [s for s in sessions['original'] if (s is not None) and (s.date=='20190828')]
  694. maze_orig = early_sessions_orig[0].maze
  695. mx.analysis.probs.arrows_plot2(early_sessions_orig, maze=maze_orig)
  696. mx.analysis.probs.arrows_plot2(late_sessions_orig, maze=maze_orig)
  697. ##
  698. mx.analysis.probs.arrows_plot2([ses], maze=ses.maze)
  699. ##
  700. arr_coords = np.zeros((8,12,2,4))
  701. for j,maze in enumerate(list(experiment_days.keys())[:]):
  702. for i,ses in enumerate(sessions[maze]):
  703. try:
  704. arr_coords[int(i/12), i%12, 0, j], arr_coords[int(i/12), i%12, 1, j] = (mx.analysis.probs.prob_plan_prob_vec(mx.analysis.iterators.first_exit(ses)))
  705. except:
  706. arr_coords[int(i/12), i%12, 0, j], arr_coords[int(i/12), i%12, 1, j] = (np.nan, np.nan)
  707. ##
  708. df = pd.DataFrame(columns=['mouse', 'maze', 'date', 'prob_plan', 'prob_vec'])
  709. for j,maze in enumerate(list(experiment_days.keys())[:]):
  710. for i,ses in enumerate(sessions[maze]):
  711. # try:
  712. if ses:
  713. #probs = (mx.analysis.probs.prob_plan_prob_vec(mx.analysis.iterators.first_exit(ses)))
  714. #steps = ses.steps()
  715. steps = mx.analysis.iterators.first_exit(ses)
  716. probs = (mx.analysis.probs.prob_plan_prob_vec(steps, discard_backtracked=True, only_forward=False, neither_plan_nor_nav=True, spatial_distance='manhattan'))
  717. df = df.append({'mouse':ses.subject, 'maze':maze, 'date':ses.date, 'prob_plan':probs[0], 'prob_vec':probs[1]}, ignore_index=True)
  718. # except:
  719. # pass
  720. ##
  721. plt.figure()
  722. ax = plt.gca()
  723. #ax = df[df['maze']==maze].plot(kind='scatter', x='prob_vec', y='prob_plan')
  724. for i,maze in enumerate(list(experiment_days.keys())[:]):
  725. df[df['maze']==maze].plot(kind='scatter', x='prob_vec', y='prob_plan', ax=ax, label=maze, color=sns.color_palette()[i])
  726. plt.xlim(0,1)
  727. plt.ylim(0,1)
  728. plt.legend()
  729. ##
  730. plt.figure()
  731. ax = plt.gca()
  732. #ax = df[df['maze']==maze].plot(kind='scatter', x='prob_vec', y='prob_plan')
  733. for i,maze in enumerate(list(experiment_days.keys())[:]):
  734. df[df['maze']==maze].groupby('date').mean().plot(kind='line', x='prob_vec', y='prob_plan', ax=ax, label=maze, color=sns.color_palette()[i])
  735. #plt.xlim(0,1)
  736. #plt.ylim(0,1)
  737. plt.legend()
  738. ##
  739. # Multinomial regression
  740. ##
  741. sq_figsize = (6.5,6)
  742. from concurrent.futures import ProcessPoolExecutor
  743. problem_2vars = {
  744. 'num_vars': 2,
  745. 'names': ['gamma', 'xi'],
  746. 'bounds': [[-10,10], [-10,10]]
  747. }
  748. param_values_2vars = saltelli.sample(problem_2vars, 2, calc_second_order=True)
  749. problem_3vars = {
  750. 'num_vars': 3,
  751. 'names': ['gamma', 'delta', 'xi'],
  752. 'bounds': [[-10,10], [-10,10], [-10,10]]
  753. }
  754. param_values_3vars = saltelli.sample(problem_3vars, 2, calc_second_order=True)
  755. problem_4vars = {
  756. 'num_vars': 4,
  757. 'names': ['gamma', 'delta', 'epsilon', 'xi'],
  758. 'bounds': [[-10,10], [-10,10], [-10,10], [-10,10]]
  759. }
  760. param_values_4vars = saltelli.sample(problem_4vars, 2, calc_second_order=True)
  761. ##
  762. day_idxs = list(range(10))
  763. centrality_measure='betweenness'
  764. #day_idxs = [0, 3, 6, 9]
  765. #regr_coeffs = pd.DataFrame(columns=['maze', 'exp_day', 'mouse', 'vector', 'optimal', 'centrality', 'previous'])
  766. regr_coeffs_red = pd.DataFrame(columns=['maze', 'exp_day', 'mouse', 'vector', 'optimal', 'previous'])
  767. super_likelihoods = []
  768. for maze in ['fully','original','maze1','maze2']:
  769. for day_i in day_idxs:
  770. for mouse in mice:
  771. experiment_day_list = experiment_days[maze][day_i]
  772. experiment_day_str = experiment_day_list[0] + experiment_day_list[1] + experiment_day_list[2]
  773. super_likelihoods.extend([mx.fitting.MixtureLikelihood(s, centrality=centrality_measure) for s in sessions[maze] if s and s.date == experiment_day_str and s.subject == mouse])
  774. # ---------------------------Three Components---------------------------------
  775. # Vector navigation and planning
  776. # ----------------------
  777. def min_super_gdx_nll(v):
  778. opt_res = {}
  779. for seslike in super_likelihoods:
  780. opt_res[seslike.session.subject] = minimize(
  781. seslike.gdx_nll, v, method='Nelder-Mead')
  782. return opt_res
  783. per_mouse_opt = {}
  784. per_mouse_nll = {}
  785. per_mouse_x_val = {}
  786. per_mouse_best_nll = {}
  787. per_mouse_best_x_val = {}
  788. for mouse in mice:
  789. per_mouse_opt[mouse] = []
  790. per_mouse_nll[mouse] = []
  791. per_mouse_x_val[mouse] = []
  792. per_mouse_best_nll[mouse] = float('inf')
  793. per_mouse_best_x_val[mouse] = np.zeros(3)
  794. with ProcessPoolExecutor() as executor:
  795. #mega_opt_res = list(executor.map(min_nll, param_values_4vars))
  796. for r in executor.map(min_super_gdx_nll, param_values_3vars):
  797. for mouse in mice:
  798. try:
  799. per_mouse_opt[mouse].append(r[mouse])
  800. per_mouse_nll[mouse].append(r[mouse]['fun'])
  801. per_mouse_x_val[mouse].append(r[mouse]['x'])
  802. if r[mouse]['fun'] < per_mouse_best_nll[mouse]:
  803. per_mouse_best_x_val[mouse] = r[mouse]['x']
  804. per_mouse_best_nll[mouse] = r[mouse]['fun']
  805. except:
  806. per_mouse_opt[mouse].append(np.nan)
  807. per_mouse_nll[mouse].append(np.nan)
  808. per_mouse_x_val[mouse].append(np.nan)
  809. #if '4IV' in mice:
  810. # mice.remove('4IV')
  811. for mouse in mice:
  812. regr_coeffs_red = regr_coeffs_red.append({'maze':maze, 'exp_day':day_i, 'mouse':mouse,
  813. 'vector':per_mouse_best_x_val[mouse][0],
  814. 'optimal':per_mouse_best_x_val[mouse][1],
  815. 'previous':per_mouse_best_x_val[mouse][2]*0.125},
  816. ignore_index=True)
  817. if False:
  818. pl.figure(figsize=sq_figsize)
  819. for mouse in mice:
  820. pl.plot([1,2,3], per_mouse_best_x_val[mouse]*np.array([1,1,0.125]), label=mouse, linewidth=0,
  821. marker='o')
  822. pl.xlim(0.5, 3.5)
  823. pl.xticks([1,2,3], ['Vector nav.', 'Planning', r'$\xi$ penalty'], rotation=17)
  824. pl.ylim(-0.2, 0.8)
  825. pl.title('Mixture component weights for all trials. Maze: {} Day: {}'.format(maze, day_i))
  826. pl.tight_layout()
  827. gdx_best_nll = copy.deepcopy(per_mouse_best_nll)
  828. if False:
  829. def min_super_gdzx_nll(v):
  830. opt_res = {}
  831. for seslike in super_likelihoods:
  832. opt_res[seslike.session.subject] = minimize(seslike.gdzx_nll, v, method='Nelder-Mead')
  833. return opt_res
  834. per_mouse_opt = {}
  835. per_mouse_nll = {}
  836. per_mouse_x_val = {}
  837. per_mouse_best_nll = {}
  838. per_mouse_best_x_val = {}
  839. for mouse in mice:
  840. per_mouse_opt[mouse] = []
  841. per_mouse_nll[mouse] = []
  842. per_mouse_x_val[mouse] = []
  843. per_mouse_best_nll[mouse] = float('inf')
  844. per_mouse_best_x_val[mouse] = np.zeros(4)
  845. with ProcessPoolExecutor(max_workers=20) as executor:
  846. #mega_opt_res = list(executor.map(min_nll, param_values_4vars))
  847. for r in executor.map(min_super_gdzx_nll, param_values_4vars):
  848. for mouse in mice:
  849. try:
  850. per_mouse_opt[mouse].append(r[mouse])
  851. per_mouse_nll[mouse].append(r[mouse]['fun'])
  852. per_mouse_x_val[mouse].append(r[mouse]['x'])
  853. if r[mouse]['fun'] < per_mouse_best_nll[mouse]:
  854. per_mouse_best_x_val[mouse] = r[mouse]['x']
  855. per_mouse_best_nll[mouse] = r[mouse]['fun']
  856. except:
  857. per_mouse_opt[mouse].append(np.nan)
  858. per_mouse_nll[mouse].append(np.nan)
  859. per_mouse_x_val[mouse].append(np.nan)
  860. for mouse in mice:
  861. regr_coeffs = regr_coeffs.append({'maze':maze, 'exp_day':day_i, 'mouse':mouse,
  862. 'vector':per_mouse_best_x_val[mouse][0],
  863. 'optimal':per_mouse_best_x_val[mouse][1],
  864. 'centrality':per_mouse_best_x_val[mouse][2],
  865. 'previous':per_mouse_best_x_val[mouse][3]*0.125},
  866. ignore_index=True)
  867. if False:
  868. pl.figure(figsize=sq_figsize)
  869. for mouse in mice:
  870. pl.plot([1,2,3,4], per_mouse_best_x_val[mouse]*np.array([1,1,1,0.125]), linewidth=0, marker='o')
  871. pl.xlim(0,5)
  872. pl.xticks([1,2,3,4], ['Vector nav.', 'Planning', 'Centrality', r'$\xi$ penalty'], rotation=17)
  873. pl.title('Mixture component weights for all trials. Maze: {} Day: {}'.format(maze, day_i))
  874. pl.tight_layout()
  875. gdzx_best_nll = copy.deepcopy(per_mouse_best_nll)
  876. ##
  877. regr_coeffs_red.to_pickle('regr_coeffs_red.pkl')
  878. ##
  879. regr_coeffs.to_pickle('regr_coeffs_node_between.pkl')
  880. ##
  881. regr_coeffs = pd.read_pickle('regr_coeffs.pkl')
  882. ##
  883. for maze in ['fully','original','maze1','maze2']:
  884. #std = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').std()
  885. sem = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').sem()
  886. regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').mean().plot(kind='line', y=['vector', 'optimal', 'centrality', 'previous'], yerr=sem)
  887. #std = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').std()
  888. #regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').median().plot(kind='line', y=['vector', 'optimal', 'centrality', 'previous'], yerr=std)
  889. plt.title(maze)
  890. #plt.ylim(-2, 2)
  891. plt.ylim(0, 1.5)
  892. plt.ylim(0, 1)
  893. ##
  894. for maze in ['fully','original','maze1','maze2']:
  895. #std = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').std()
  896. sem = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').sem()
  897. regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').mean().plot(kind='line', y=['vector', 'optimal', 'previous'], yerr=sem)
  898. #std = regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').std()
  899. #regr_coeffs.query('maze=="{}"'.format(maze)).groupby('exp_day').median().plot(kind='line', y=['vector', 'optimal', 'centrality', 'previous'], yerr=std)
  900. plt.title(maze)
  901. #plt.ylim(-2, 2)
  902. plt.ylim(0, 1.5)
  903. plt.ylim(0, 1)
  904. ##
  905. for f in range(11, 37):
  906. pl.figure(f)
  907. pl.ylim([-0.2, 1.6])
  908. ##
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...