-
Notifications
You must be signed in to change notification settings - Fork 33
/
Neurons.py
2946 lines (2467 loc) · 145 KB
/
Neurons.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
import ratinabox
import copy
import warnings
import pprint
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import scipy
from scipy import stats as stats
import warnings
from matplotlib.collections import EllipseCollection
from ratinabox import utils
"""NEURONS"""
"""Parent Class"""
class Neurons:
"""The Neuron class defines a population of Neurons. All Neurons have firing rates which depend on the state of the Agent. As the Agent moves the firing rate of the cells adjust accordingly.
All Neuron classes must be initalised with the Agent (to whom these cells belong) since the Agent determines the firingrates through its position and velocity. The Agent class will itself contain the Environment. Both the Agent (position/velocity) and the Environment (geometry, walls, objects etc.) determine the firing rates. Optionally (but likely) an input dictionary 'params' specifying other params will be given.
This is a generic Parent class. We provide several SubClasses of it. These include:
• PlaceCells()
• GridCells()
• BoundaryVectorCells()
• ObjectVectorCells()
• AgentVectorCells()
• FieldOfViewBVCs()
• FieldOfViewOVCs()
• FieldOfViewAVCs()
• VelocityCells()
• HeadDirectionCells()
• SpeedCells()
• FeedForwardLayer()
• RandomSpatialNeurons()
as well as (in the contribs)
• ValueNeuron()
• NeuralNetworkNeurons()
The unique function in each child classes is get_state(). Whenever Neurons.update() is called Neurons.get_state() is then called to calculate and return the firing rate of the cells at the current moment in time. This is then saved. In order to make your own Neuron subclass you will need to write a class with the following mandatory structure:
============================================================================================
MyNeuronClass(Neurons):
default_params = {'a_default_param":3.14159} # default params dictionary is defined in the preamble, as a class attribute. Note its values are passed upwards and used in all the parents classes of your class.
def __init__(self,
Agent,
params={}): #<-- do not change these
self.params = copy.deepcopy(__class__.default_params) # to get the default param dictionary of the current class, defined in the preamble, use __class__. Then, make sure to deepcopy it, as only making a shallow copy can have unintended consequences (i.e., any modifications to it would be propagated to ALL instances of this class!).
self.params.update(params)
super().__init__(Agent,self.params)
def get_state(self,
evaluate_at='agent',
**kwargs) #<-- do not change these
firingrate = .....
###
Insert here code which calculates the firing rate.
This may work differently depending on what you set evaluate_at as. For example, evaluate_at == 'agent' should mean that the position or velocity (or whatever determines the firing rate) will by evaluated using the agents current state. You might also like to have an option like evaluate_at == "all" (all positions across an environment are tested simultaneously - plot_rate_map() tries to call this, for example) or evaluate_at == "last" (in a feedforward layer just look at the last firing rate saved in the input layers saves time over recalculating them.). **kwargs allows you to pass position or velocity in manually.
By default, the Neurons.update() calls Neurons.get_state() rwithout passing any arguments. So write the default behaviour of get_state() to be what you want it to do in the main training loop, .
###
return firingrate
def any_other_functions_you_might_want(self):...
============================================================================================
As we have written them, Neuron subclasses which have well defined ground truth spatial receptive fields (PlaceCells, GridCells but not VelocityCells etc.) can also be queried for any arbitrary pos/velocity (i.e. not just the Agents current state) by passing these in directly to the function "get_state(evaluate_at='all') or get_state(evaluate_at=None, pos=my_array_of_positons)". This calculation is vectorised and relatively fast, returning an array of firing rates one for each position. It is what is used when you try Neuron.plot_rate_map().
List of key functions...
..that you're likely to use:
• update()
• plot_rate_timeseries()
• plot_rate_map()
...that you might not use but could be useful:
• save_to_history()
• reset_history()
• boundary_vector_preference_function()
"""
default_params = {
"n": 10,
"name": "Neurons",
"color": None, # just for plotting
"noise_std": 0, # 0 means no noise, std of the noise you want to add (Hz)
"noise_coherence_time": 0.5,
"min_fr":0.0, #not all cells use max_fr nd min_fr but we define them here in the parent class for those that do
"max_fr":1.0,
"save_history": True, # whether to save history (set to False if you don't intend to access Neuron.history for data after, for better memory performance)
}
def __init__(self, Agent, params={}):
"""Initialise Neurons(), takes as input a parameter dictionary. Any values not provided by the params dictionary are taken from a default dictionary below.
Args:
Agent. The RatInABox Agent these cells belong to.
params (dict, optional). Defaults to {}.
Typically you will not actually initialise a Neurons() class, instead you will initialised by one of it's subclasses.
"""
self.Agent = Agent
self.Agent.Neurons.append(self)
self.params = copy.deepcopy(__class__.default_params)
self.params.update(params)
utils.update_class_params(self, self.params, get_all_defaults=True)
utils.check_params(self, params.keys())
self.firingrate = np.zeros(self.n)
self.noise = np.zeros(self.n)
self.history = {}
self.history["t"] = []
self.history["firingrate"] = []
self.history["spikes"] = []
self._last_history_array_cache_time = None
self._history_arrays = {} # this dictionary is the same as self.history except the data is in arrays not lists BUT it should only be accessed via its getter-function `self.get_history_arrays()`. This is because the lists are only converted to arrays when they are accessed, not on every step, so as to save time.
self.colormap = "inferno" # default colormap for plotting ratemaps
if ratinabox.verbose is True:
print(
f"\nA Neurons() class has been initialised with parameters f{self.params}. Use Neurons.update() to update the firing rate of the Neurons to correspond with the Agent.Firing rates and spikes are saved into the Agent.history dictionary. Plot a timeseries of the rate using Neurons.plot_rate_timeseries(). Plot a rate map of the Neurons using Neurons.plot_rate_map()."
)
@classmethod
def get_all_default_params(cls, verbose=False):
"""Returns a dictionary of all the default parameters of the class, including those inherited from its parents."""
all_default_params = utils.collect_all_params(cls, dict_name="default_params")
if verbose:
pprint.pprint(all_default_params)
return all_default_params
def update(self, **kwargs):
"""Update the firing rate of the Neurons() class. This is called by the Agent.update() function. This core function should be called by the user on each loop in order to refresh the firing rate of the Neurons() class in line with the Agent's current state. It will also save the firing rate and spikes to the Agent.history dictionary if self.save_history is True.
Args:
• kwargs will be passed into get_state()
"""
# update noise vector
dnoise = utils.ornstein_uhlenbeck(
dt=self.Agent.dt,
x=self.noise,
drift=0,
noise_scale=self.noise_std,
coherence_time=self.noise_coherence_time,
)
self.noise = self.noise + dnoise
# update firing rate
if np.isnan(self.Agent.pos[0]):
firingrate = np.zeros(self.n) # returns zero if Agent position is nan
else:
firingrate = self.get_state(**kwargs)
self.firingrate = firingrate.reshape(-1)
self.firingrate = self.firingrate + self.noise
if self.save_history is True:
self.save_to_history()
return
def get_state(self, **kwargs):
raise NotImplementedError("Neurons object needs a get_state() method")
def get_head_direction_averaged_state(self, evaluate_at="agent", angular_resolution_degrees=10, **kwargs):
"""Like get_state() except it calculates it at all head directions 0-->2pi and then averages over those head directions. Note this will only be relevant (although it will always "work") for Neurons which have some kind of head direction selectivity i.e. Neurons where "head_direction" is a kwarg which is used by get_state(). These include HeadDirectionCells or egocentric-BoundaryVectorCells or any cells you might build out of these. Conversely for PlaceCells, the head_direction argument into get_state() will be ignored so this will just be a more inefficient way of calling get_state().
Args:
• evaluate_at: "agent" or "all" or None. If "agent" (default) then the Agent's current position is used to calculate the firing rate. If "all" then the firing rate is calculated at all positions across the environment. If None then you must provide a position or velocity array as a kwarg "pos" or "vel" respectively. Defaults to "agent".
• angular_resolution_degrees: the angular resolution in degrees at which to calculate the firing rate. Defaults to 10.
• kwargs: passed into get_state().
"""
firingrate = np.zeros_like(self.get_state(evaluate_at=evaluate_at, head_direction=[1,0], **kwargs))
n_angles = int(360 / angular_resolution_degrees)
firingrate = np.repeat(firingrate[:,:,np.newaxis],n_angles,axis=2)
angles = np.linspace(0,2*np.pi,n_angles)
for (i,ang) in enumerate(angles):
head_direction = np.array([np.cos(ang),np.sin(ang)])
firingrate[:,:,i] = self.get_state(evaluate_at=evaluate_at, head_direction=head_direction, **kwargs)
firingrate = np.mean(firingrate,axis=2)
return firingrate
def plot_rate_timeseries(
self,
t_start=0.0,
t_end=None,
chosen_neurons="all",
spikes=False,
imshow=False,
fig=None,
ax=None,
xlim=None,
color=None,
background_color=None,
autosave=None,
**kwargs,
):
"""Plots a timeseries of the firing rate of the neurons between t_start and t_end
Args:
• t_start (int, optional): _description_. Defaults to start of data, probably 0.
• t_end (int, optional): _description_. Defaults to end of data.
• chosen_neurons: Which neurons to plot. string "10" or 10 will plot ten of them, "all" will plot all of them, "12rand" will plot 12 random ones. A list like [1,4,5] will plot cells indexed 1, 4 and 5. Defaults to "all".
chosen_neurons (str, optional): Which neurons to plot. string "10" will plot 10 of them, "all" will plot all of them, a list like [1,4,5] will plot cells indexed 1, 4 and 5. Defaults to "10".
• spikes (bool, optional): If True, scatters exact spike times underneath each curve of firing rate. Defaults to False.
the below params I just added for help with animations
• imshow - if True will not dispaly as mountain plot but as an image (plt.imshow). Thee "extent" will be (t_start, t_end, 0, 1) in case you want to plot on top of this
• fig, ax: the figure, axis to plot on (can be None)
• xlim: fix xlim of plot irrespective of how much time you're plotting
• color: color of the line, if None, defaults to cell class default (probalby "C1")
• background_color: color of the background if not matplotlib default (probably white)
• autosave: if True, will try to save the figure to the figure directory `ratinabox.figure_directory`. Defaults to None in which case looks for global constant ratinabox.autosave_plots
• kwargs sent to mountain plot function, you can ignore these
Returns:
fig, ax
"""
history_arrays = self.get_history_arrays() #gets history data as dictionary of arrays
t = history_arrays["t"]
t_end = t_end or t[-1]
slice = self.Agent.get_history_slice(t_start, t_end)
rate_timeseries = history_arrays["firingrate"][slice]
spike_data = history_arrays["spikes"][slice]
t = t[slice]
# neurons to plot
chosen_neurons = self.return_list_of_neurons(chosen_neurons)
n_neurons_to_plot = len(chosen_neurons)
spike_data = spike_data[:, chosen_neurons]
rate_timeseries = rate_timeseries[:, chosen_neurons]
was_fig, was_ax = (fig is None), (
ax is None
) # remember whether a fig or ax was provided as xlims depend on this
if color is None:
color = self.color
if imshow == False:
firingrates = rate_timeseries.T
fig, ax = utils.mountain_plot(
X=t / 60,
NbyX=firingrates,
color=color,
xlabel="Time / min",
ylabel="Neurons",
xlim=None,
fig=fig,
ax=ax,
**kwargs,
)
if spikes == True:
for i in range(len(chosen_neurons)):
time_when_spiked = t[spike_data[:, i]] / 60
h = (i + 1 - 0.1) * np.ones_like(time_when_spiked)
ax.scatter(
time_when_spiked,
h,
color=(self.color if self.color is not None else "C1"),
alpha=0.5,
s=5,
linewidth=0,
)
xmin = t_start / 60 if was_fig else min(t_start / 60, ax.get_xlim()[0])
xmax = t_end / 60 if was_fig else max(t_end / 60, ax.get_xlim()[1])
ax.set_xlim(
left=xmin,
right=xmax,
)
ax.set_xticks([xmin, xmax])
ax.set_xticklabels([round(xmin, 2), round(xmax, 2)])
if xlim is not None:
ax.set_xlim(right=xlim / 60)
ax.set_xticks([round(t_start / 60, 2), round(xlim / 60, 2)])
ax.set_xticklabels([round(t_start / 60, 2), round(xlim / 60, 2)])
if background_color is not None:
ax.set_facecolor(background_color)
fig.patch.set_facecolor(background_color)
elif imshow == True:
if fig is None and ax is None:
fig, ax = plt.subplots(
figsize=(
ratinabox.MOUNTAIN_PLOT_WIDTH_MM / 25,
0.5 * ratinabox.MOUNTAIN_PLOT_WIDTH_MM / 25,
)
)
data = rate_timeseries.T
ax.imshow(
data[::-1],
aspect="auto",
# aspect=0.5 * data.shape[1] / data.shape[0],
extent=(t_start, t_end, 0, 1),
)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.set_xlabel("Time / min")
ax.set_xticks([t_start, t_end])
ax.set_xticklabels([round(t_start / 60, 2), round(t_end / 60, 2)])
ax.set_yticks([])
ax.set_ylabel("Neurons")
ratinabox.utils.save_figure(fig, self.name + "_firingrate", save=autosave)
return fig, ax
def plot_rate_map(
self,
chosen_neurons="all",
method="groundtruth",
spikes=False,
fig=None,
ax=None,
shape=None,
colorbar=True,
t_start=0,
t_end=None,
autosave=None,
**kwargs,
):
"""Plots rate maps of neuronal firing rates across the environment
Args:
•chosen_neurons: Which neurons to plot. string "10" will plot 10 of them, "all" will plot all of them, a list like [1,4,5] will plot cells indexed 1, 4 and 5. Defaults to "10".
• method: "groundtruth" "history" "neither" "ratemaps_provided": which method to use. If "groundtruth" (default) tries to calculate rate map by evaluating firing rate at all positions across the environment (note this isn't always well defined. in which case...). If "groundtruth_headdirectionaveraged" calculates rate maps but averaged over all head directions (2D environments only). If "history", plots ratemap by a weighting a histogram of positions visited by the firingrate observed at that position. If "neither" (or anything else), then neither. If "ratemaps_provided" then you must provide a rate map as a numpy array of shape (n_neurons, n_positions) under the keyworkd argument "ratemaps". This is useful if you have already calculated the rate map and want to plot it without having to recalculate it.
• spikes: True or False. Whether to display the occurence of spikes. If False (default) no spikes are shown. If True both ratemap and spikes are shown.
• fig, ax (the fig and ax to draw on top of, optional)
• shape is the shape of the multipanel figure, must be compatible with chosen neurons
• colorbar: whether to show a colorbar
• t_start, t_end: in the case where you are plotting spike, or using historical data to get rate map, this restricts the timerange of data you are using
• autosave: if True, will try to save the figure to the figure directory `ratinabox.figure_directory`. Defaults to None in which case looks for global constant ratinabox.autosave_plots
• kwargs are sent to get_state and utils.mountain_plot and can be ignore if you don't need to use them
Returns:
fig, ax
"""
#Set kwargs (TODO make lots of params accessible here as kwargs)
spikes_color = kwargs.get("spikes_color", self.color) or "C1"
spikes_size = kwargs.get("spikes_size", (5 if self.Agent.Environment.dimensionality == "2D" else 2))
color = kwargs.pop("color", self.color) or "C1"
bin_size = kwargs.get("bin_size", 0.04) #only relevant if you are plotting by method="history"
optimise_plot_for_single_neuron = kwargs.get("optimise_plot_for_single_neuron", False) #if True will optimise the plot for when you are only visualising the rate map of a single neuron (e.g. chosen_neurons = [5], if False will plot as a mountain plot
# GET DATA
if method[:11] == "groundtruth":
try:
if method == "groundtruth":
rate_maps = self.get_state(evaluate_at="all", **kwargs)
elif method == "groundtruth_headdirectionaveraged":
rate_maps = self.get_head_direction_averaged_state(evaluate_at="all", **kwargs)
except Exception as e:
print(
"It was not possible to get the rate map by evaluating the firing rate at all positions across the Environment. This is probably because the Neuron class does not support vectorised evaluation, or it does not have an groundtruth receptive field. Instead trying wit ha for-loop over all positions one-by-one (could be slow)Instead, plotting rate map by weighted position histogram method. Here is the error:"
)
print("Error: ", e)
import traceback
traceback.print_exc()
method = "history"
if method == "history" or spikes == True:
history_data = self.get_history_arrays() # converts lists to arrays (if this wasn't just done) and returns them in a dict same as self.history but with arrays not lists
t = history_data["t"]
# times to plot
if len(t) == 0:
print("Can't plot rate map by method='history', nor plot spikes, since there is no available data to plot. ")
return
t_end = t_end or t[-1]
position_data_agent = kwargs.get("position_data_agent", self.Agent) # In rare cases you may like to plot this cells rate/spike data against the position of a diffferent Agent. This kwarg enables that.
position_agent_history_data = position_data_agent.get_history_arrays()
slice = position_data_agent.get_history_slice(t_start, t_end)
pos = position_agent_history_data["pos"][slice]
t = t[slice]
if method == "history":
rate_timeseries = history_data["firingrate"][slice].T
if len(rate_timeseries) == 0:
print("No historical data with which to calculate ratemap.")
if spikes == True:
spike_data = history_data["spikes"][slice].T
if len(spike_data) == 0:
print("No historical data with which to plot spikes.")
if method == "ratemaps_provided":
try:
rate_maps = kwargs["ratemaps"]
except:
print(
"You have specified method='ratemaps_provided' but have not provided the rate maps themselves. Please provide them as a numpy array of shape (n_neurons, n_positions) under the keyworkd argument 'ratemaps'."
)
return
if self.color is None:
coloralpha = None
else:
coloralpha = list(matplotlib.colors.to_rgba(color))
coloralpha[-1] = 0.5
chosen_neurons = self.return_list_of_neurons(chosen_neurons=chosen_neurons)
N_neurons = len(chosen_neurons)
# PLOT 2D
if self.Agent.Environment.dimensionality == "2D":
from mpl_toolkits.axes_grid1 import ImageGrid
if fig is None and ax is None:
if shape is None:
Nx, Ny = len(chosen_neurons), 1
else:
Nx, Ny = shape[0], shape[1]
env_fig, env_ax = self.Agent.Environment.plot_environment(
autosave=False, **kwargs,
)
width, height = env_fig.get_size_inches()
plt.close(env_fig)
plt.show
fig = plt.figure(figsize=(width * Nx, height * Ny))
if colorbar == True and (method in ["groundtruth", "history", "groundtruth_headdirectionaveraged"]):
cbar_mode = "single"
else:
cbar_mode = None
axes = ImageGrid(
fig,
111,
nrows_ncols=(Ny, Nx),
axes_pad=0.05,
cbar_location="right",
cbar_mode=cbar_mode,
cbar_size="5%",
cbar_pad=0.05,
)
if colorbar == True:
cax = axes.cbar_axes[0]
axes = np.array(axes)
else:
axes = np.array([ax]).reshape(-1)
if method in ["groundtruth", "history"]:
if colorbar == True:
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(axes[-1])
cax = divider.append_axes("right", size="5%", pad=0.05)
for i, ax_ in enumerate(axes):
_, ax_ = self.Agent.Environment.plot_environment(
fig, ax_, autosave=False, **kwargs
)
if len(chosen_neurons) != axes.size:
print(
f"You are trying to plot a different number of neurons {len(chosen_neurons)} than the number of axes provided {axes.size}. Some might be missed. Either change this with the chosen_neurons argument or pass in a list of axes to plot on"
)
vmin, vmax = 0, 0
ims = []
if method in ["groundtruth", "history", "groundtruth_headdirectionaveraged"]:
for i, ax_ in enumerate(axes):
ex = self.Agent.Environment.extent
if method[:11] == "groundtruth":
rate_map = rate_maps[chosen_neurons[i], :].reshape(
self.Agent.Environment.discrete_coords.shape[:2]
)
im = ax_.imshow(rate_map, extent=ex, zorder=0, cmap=self.colormap,
interpolation="bicubic", # smooths rate maps but this does slow down the plotting a bit
)
elif method == "history":
default_2D_bin_size = 0.05
bin_size = kwargs.get("bin_size", default_2D_bin_size)
rate_timeseries_ = rate_timeseries[chosen_neurons[i], :]
rate_map, zero_bins = utils.bin_data_for_histogramming(
data=pos,
extent=ex,
dx=bin_size,
weights=rate_timeseries_,
norm_by_bincount=True,
return_zero_bins=True,
)
#rather than just "nan-ing" the regions where no data was observed we'll plot ontop a "mask" overlay which blocks with a grey square regions where no data was observed. The benefit of this technique is it still allows us to use "bicubic" interpolation which is much smoother than the default "nearest" interpolation.
binary_colors = [(0,0,0,0),ratinabox.LIGHTGREY] #transparent if theres data, grey if there isn't
binary_cmap = matplotlib.colors.ListedColormap(binary_colors)
im = ax_.imshow(
rate_map,
extent=ex,
cmap=self.colormap,
interpolation="bicubic",
zorder=0,
)
no_data_mask = ax_.imshow(
zero_bins,
extent=ex,
cmap=binary_cmap,
interpolation="nearest",
zorder=0.001,
)
ims.append(im)
vmin, vmax = (
min(vmin, np.min(rate_map)),
max(vmax, np.max(rate_map)),
)
if "zero_center" in kwargs.keys(): #good for diverging colormaps, makes sure the colorbar is centered on zero
if kwargs["zero_center"] == True:
vmax = max(abs(vmin), abs(vmax))
vmin = -vmax
for im in ims:
im.set_clim((vmin, vmax))
if colorbar == True:
cbar = plt.colorbar(ims[-1], cax=cax)
cbar.ax.tick_params(length=0)
cbar.set_label("Firing rate / Hz",labelpad=-10)
# lim_v = vmax if vmax > -vmin else vmin
cbar.set_ticks([vmin,vmax])
cbar.set_ticklabels([f"{vmin:.1f}", f"{vmax:.1f}"])
cbar.outline.set_visible(False)
if spikes is True:
for i, ax_ in enumerate(axes):
pos_where_spiked = pos[spike_data[chosen_neurons[i], :]]
ax_.scatter(
pos_where_spiked[:, 0],
pos_where_spiked[:, 1],
s=spikes_size,
linewidth=0,
alpha=0.7,
zorder=1.2,
color=spikes_color,
)
# PLOT 1D
elif self.Agent.Environment.dimensionality == "1D":
zero_bins = None
if method == "groundtruth":
rate_maps = rate_maps[chosen_neurons, :]
x = self.Agent.Environment.flattened_discrete_coords[:, 0]
if method == "history":
ex = self.Agent.Environment.extent
default_1D_bin_size = 0.01
bin_size = kwargs.get("bin_size", default_1D_bin_size)
pos_ = pos[:, 0]
rate_maps = []
for neuron_id in chosen_neurons:
(rate_map, x, zero_bins) = utils.bin_data_for_histogramming(
data=pos_,
extent=ex,
dx=bin_size,
weights=rate_timeseries[neuron_id, :],
norm_by_bincount=True,
return_zero_bins=True,
)
resolution_increase = 10
x, rate_map = utils.interpolate_and_smooth(x, rate_map, sigma=0.01, resolution_increase=resolution_increase)
rate_maps.append(rate_map)
zero_bins = np.repeat(zero_bins, resolution_increase)
rate_maps = np.array(rate_maps)
if fig is None and ax is None:
fig, ax = plt.subplots(
figsize=(
ratinabox.MOUNTAIN_PLOT_WIDTH_MM / 25,
N_neurons * ratinabox.MOUNTAIN_PLOT_SHIFT_MM / 25,
)
)
fig, ax = self.Agent.Environment.plot_environment(
autosave=False, fig=fig, ax=ax
)
if method != "neither":
if (N_neurons > 1 or
(N_neurons == 1 and optimise_plot_for_single_neuron == False)):
fig, ax = utils.mountain_plot(
X=x, NbyX=rate_maps, color=color, nan_bins=zero_bins, fig=fig, ax=ax, ylabel="Neurons", **kwargs)
if N_neurons == 1 and optimise_plot_for_single_neuron == False:
warnings.warn("Use kwarg `optimise_plot_for_single_neuron = True` to optimise this plot when visualising the rate map of a single neuron.")
else:
# If there is only one neuron passed this is a special case and we won't use mountain plot
X_ = x.copy()
c = color if color is not None else "C1"
c = np.array(matplotlib.colors.to_rgb(c))
fc = 0.3 * c + (1 - 0.3) * np.array([1, 1, 1])
if zero_bins is not None: X_[zero_bins] = np.nan
ax.plot(X_, rate_maps[0], color=color, linewidth=1)
ax.fill_between(X_, rate_maps[0], 0, alpha=0.8, color=fc)
ax.spines['left'].set_visible(True)
ax.spines['left'].set_position(('outward', 0))
ax.spines['bottom'].set_position(('data', 0))
fig.set_figheight(0.15*ratinabox.MOUNTAIN_PLOT_WIDTH_MM / 25,)
ax.set_ylabel("Firing rate\n/ Hz")
y_min, y_max = ax.get_ylim()
ax.set_yticks([y_min, y_max])
#remove the first tick label so it doesn't overlap with the y-axis label
x_ticks = ax.get_xticks()
if x_ticks[0] == 0:
ax.set_xticks(x_ticks[1:])
if spikes is True:
for i in range(len(chosen_neurons)):
pos_ = pos[:, 0]
pos_where_spiked = pos_[spike_data[chosen_neurons[i]]]
h = (i + 1 - 0.1) * np.ones_like(pos_where_spiked)
ax.scatter(
pos_where_spiked,
h,
color=spikes_color,
alpha=0.5,
s=spikes_size,
linewidth=0,
)
ax.set_xlabel("Position / m")
axes = ax
ratinabox.utils.save_figure(fig, self.name + "_ratemaps", save=autosave)
return fig, axes
def plot_angular_rate_map(self, chosen_neurons="all", fig=None, ax=None, autosave=None):
"""Plots the position-averaged firing rate map of the neuron as a function of head direction. To do this it calculates the spatial receptive fields at many head directions and averages them over position (therefore it may be slow).
Args:
chosen_neurons (str, optional): The neurons to plot. Defaults to "all".
fig, ax (_type_, optional): matplotlib fig, ax objects ot plot onto (optional).
autosave (bool, optional): if True, will try to save the figure into `ratinabox.figure_directory`.
Defaults to None in which case looks for global constant ratinabox.autosave_plots
"""
chosen_neurons = self.return_list_of_neurons(chosen_neurons=chosen_neurons)
if fig is None and ax is None:
fig, ax = plt.subplots(
1,
len(chosen_neurons),
figsize=(2 * len(chosen_neurons), 2),
subplot_kw={"projection": "polar"},
)
ax = np.array(ax).reshape(-1)
# get rate maps at all head directions and all positions
# the object will end up having shape (n_neurons, n_positions, n_headdirections)
rm = np.zeros_like(self.get_state(evaluate_at='all',head_direction=np.array([1,0])))
rm = np.repeat(rm[:,:,np.newaxis],100,axis=2)
angles = np.linspace(0,2*np.pi,100)
for (i,ang) in enumerate(angles):
head_direction = np.array([np.cos(ang),np.sin(ang)])
rm[:,:,i] = self.get_state(evaluate_at='all', head_direction=head_direction)
# average over positions leaving just head direction selectivity
rm_hd = np.mean(rm,axis=1)
# plot head direction rate map
for (i,n) in enumerate(chosen_neurons):
perneuron_rm = rm_hd[n,:]
ax[i].plot(angles,perneuron_rm,linewidth=2,color=self.color)
ax[i].set_yticks([])
ax[i].set_xticks([])
ax[i].set_xticks([0, np.pi / 2, np.pi, 3 * np.pi / 2])
ax[i].fill_between(angles, perneuron_rm, 0, alpha=0.2,facecolor=self.color)
ax[i].set_ylim([0, 1.1*np.max(rm_hd[n,:])])
ax[i].tick_params(pad=-20)
ax[i].set_xticklabels(["E", "N", "W", "S"])
# for i, ax_ in enumerate(axes):
# _, ax_ = self.Agent.Environment.plot_environment(
# fig, ax_, autosave=False, **kwargs
# )
ratinabox.utils.save_figure(fig, self.name + "_angularratemaps", save=autosave)
return fig, ax
def save_to_history(self):
cell_spikes = np.random.uniform(0, 1, size=(self.n,)) < (
self.Agent.dt * self.firingrate
)
self.history["t"].append(self.Agent.t)
self.history["firingrate"].append(self.firingrate.tolist())
self.history["spikes"].append(cell_spikes.tolist())
def reset_history(self):
for key in self.history.keys():
self.history[key] = []
return
def animate_rate_timeseries(
self,
t_start=None,
t_end=None,
chosen_neurons="all",
fps=15,
speed_up=1,
autosave=None,
**kwargs,
):
"""Returns an animation (anim) of the firing rates, 25fps.
Should be saved using command like:
>>> anim.save("./where_to_save/animations.gif",dpi=300) #or ".mp4" etc...
To display within jupyter notebook, just call it:
>>> anim
Args:
• t_end (_type_, optional): _description_. Defaults to None.
• chosen_neurons: Which neurons to plot. string "10" or 10 will plot ten of them, "all" will plot all of them, "12rand" will plot 12 random ones. A list like [1,4,5] will plot cells indexed 1, 4 and 5. Defaults to "all".
• speed_up: #times real speed animation should come out at.
Returns:
animation
"""
plt.rcParams["animation.html"] = "jshtml" # for animation rendering in jupyter
dt = 1 / fps
if t_start == None:
t_start = self.history["t"][0]
if t_end == None:
t_end = self.history["t"][-1]
def animate_(i, fig, ax, chosen_neurons, t_start, t_max, dt, speed_up):
t = self.history["t"]
# t_start = t[0]
# t_end = t[0] + (i + 1) * speed_up * dt
t_end = t_start + (i + 1) * speed_up * dt
ax.clear()
fig, ax = self.plot_rate_timeseries(
t_start=t_start,
t_end=t_end,
chosen_neurons=chosen_neurons,
fig=fig,
ax=ax,
xlim=t_max,
autosave=False,
**kwargs,
)
plt.close()
return
fig, ax = self.plot_rate_timeseries(
t_start=0,
t_end=10 * self.Agent.dt,
chosen_neurons=chosen_neurons,
xlim=t_end,
autosave=False,
**kwargs,
)
from matplotlib import animation
anim = matplotlib.animation.FuncAnimation(
fig,
animate_,
interval=1000 * dt,
frames=int((t_end - t_start) / (dt * speed_up)),
blit=False,
fargs=(fig, ax, chosen_neurons, t_start, t_end, dt, speed_up),
)
ratinabox.utils.save_animation(anim, "rate_timeseries", save=autosave)
return anim
def return_list_of_neurons(self, chosen_neurons="all"):
"""Returns a list of indices corresponding to neurons.
Args:
which (_type_, optional): _description_. Defaults to "all".
• "all": all neurons
• "15" or 15: 15 neurons even spread from index 0 to n
• "15rand": 15 randomly selected neurons
• [4,8,23,15]: this list is returned (convertde to integers in case)
• np.array([[4,8,23,15]]): the list [4,8,23,15] is returned
"""
if type(chosen_neurons) is str:
if chosen_neurons == "all":
chosen_neurons = np.arange(self.n)
elif chosen_neurons.isdigit():
chosen_neurons = np.linspace(
0, self.n - 1, min(self.n, int(chosen_neurons))
).astype(int)
elif chosen_neurons[-4:] == "rand":
chosen_neurons = int(chosen_neurons[:-4])
chosen_neurons = np.random.choice(
np.arange(self.n), size=chosen_neurons, replace=False
)
if type(chosen_neurons) is int:
chosen_neurons = np.linspace(0, self.n - 1, min(self.n, chosen_neurons))
if type(chosen_neurons) is list:
chosen_neurons = list(np.array(chosen_neurons).astype(int))
pass
if type(chosen_neurons) is np.ndarray:
chosen_neurons = list(chosen_neurons.astype(int))
return chosen_neurons
def get_history_arrays(self):
"""Returns the history dataframe as a dictionary of numpy arrays (as opposed to lists). This getter-function only updates the self._history_arrays if the Agent/Neuron has updates since the last time it was called. This avoids expensive repeated conversion of lists to arrays during animations."""
if (self._last_history_array_cache_time != self.Agent.t):
self._history_arrays = {}
self._last_history_array_cache_time = self.Agent.t
for key in self.history.keys():
try: #will skip if for any reason this key cannot be converted to an array, so you can still save random stuff into the history dict without breaking this function
self._history_arrays[key] = np.array(self.history[key])
except: pass
return self._history_arrays
"""Specific subclasses """
class PlaceCells(Neurons):
"""The PlaceCells class defines a population of PlaceCells. This class is a subclass of Neurons() and inherits it properties/plotting functions.
Must be initialised with an Agent and a 'params' dictionary.
PlaceCells defines a set of 'n' place cells scattered across the environment. The firing rate is a functions of the distance from the Agent to the place cell centres. This function (params['description'])can be:
• gaussian (default)
• gaussian_threshold
• diff_of_gaussians
• top_hat
• one_hot
#TO-DO • tanni_harland https://pubmed.ncbi.nlm.nih.gov/33770492/
List of functions:
• get_state()
• plot_place_cell_locations()
default_params = {
"n": 10,
"name": "PlaceCells",
"description": "gaussian",
"widths": 0.20,
"place_cell_centres": None, # if given this will overwrite 'n',
"wall_geometry": "geodesic",
"min_fr": 0,
"max_fr": 1,
"name": "PlaceCells",
}
"""
default_params = {
"n": 10,
"name": "PlaceCells",
"description": "gaussian",
"widths": 0.20, # the radii
"place_cell_centres": None, # if given this will overwrite 'n',
"wall_geometry": "geodesic",
"min_fr": 0,
"max_fr": 1,
"name": "PlaceCells",
}
def __init__(self, Agent, params={}):
"""Initialise PlaceCells(), takes as input a parameter dictionary. Any values not provided by the params dictionary are taken from a default dictionary below.
Args:
params (dict, optional). Defaults to {}.
"""
self.Agent = Agent
self.params = copy.deepcopy(__class__.default_params)
self.params.update(params)
if self.params["place_cell_centres"] is None:
self.params["place_cell_centres"] = self.Agent.Environment.sample_positions(
n=self.params["n"], method="uniform_jitter"
)
elif type(self.params["place_cell_centres"]) is str:
if self.params["place_cell_centres"] in [
"random",
"uniform",
"uniform_jitter",
]:
self.params[
"place_cell_centres"
] = self.Agent.Environment.sample_positions(
n=self.params["n"], method=self.params["place_cell_centres"]
)
else:
raise ValueError(
"self.params['place_cell_centres'] must be None, an array of locations or one of the instructions ['random', 'uniform', 'uniform_jitter']"
)
else:
self.params["n"] = self.params["place_cell_centres"].shape[0]
self.place_cell_widths = self.params["widths"] * np.ones(self.params["n"])
super().__init__(Agent, self.params)
# Assertions (some combinations of boundary condition and wall geometries aren't allowed)
if self.Agent.Environment.dimensionality == "2D":
if all(
[
(
(self.wall_geometry == "line_of_sight")
or ((self.wall_geometry == "geodesic"))
),
(self.Agent.Environment.boundary_conditions == "periodic"),
(self.Agent.Environment.dimensionality == "2D"),
]
):
print(
f"{self.wall_geometry} wall geometry only possible in 2D when the boundary conditions are solid. Using 'euclidean' instead."
)
self.wall_geometry = "euclidean"
if (self.wall_geometry == "geodesic") and (
len(self.Agent.Environment.walls) > 5
):
print(
"'geodesic' wall geometry only supported for enivironments with 1 additional wall (4 bounding walls + 1 additional). Sorry. Using 'line_of_sight' instead."
)
self.wall_geometry = "line_of_sight"
if ratinabox.verbose is True:
print(
"PlaceCells successfully initialised. You can see where they are centred at using PlaceCells.plot_place_cell_locations()"
)
return
def get_state(self, evaluate_at="agent", **kwargs):
"""Returns the firing rate of the place cells.
By default position is taken from the Agent and used to calculate firinf rates. This can also by passed directly (evaluate_at=None, pos=pass_array_of_positions) or ou can use all the positions in the environment (evaluate_at="all").
Returns:
firingrates: an array of firing rates
"""
if evaluate_at == "agent":
pos = self.Agent.pos
elif evaluate_at == "all":
pos = self.Agent.Environment.flattened_discrete_coords
else:
pos = kwargs["pos"]
pos = np.array(pos)
# place cell fr's depend only on how far the agent is from cell centres (and their widths)
dist = (
self.Agent.Environment.get_distances_between___accounting_for_environment(
self.place_cell_centres, pos, wall_geometry=self.wall_geometry
)
) # distances to place cell centres
widths = np.expand_dims(self.place_cell_widths, axis=-1)
if self.description == "gaussian":
firingrate = np.exp(-(dist**2) / (2 * (widths**2)))
if self.description == "gaussian_threshold":
firingrate = np.maximum(
np.exp(-(dist**2) / (2 * (widths**2))) - np.exp(-1 / 2),
0,
) / (1 - np.exp(-1 / 2))
if self.description == "diff_of_gaussians":
ratio = 1.5
firingrate = np.exp(-(dist**2) / (2 * (widths**2))) - (
1 / ratio**2
) * np.exp(-(dist**2) / (2 * ((ratio * widths) ** 2)))
firingrate *= ratio**2 / (ratio**2 - 1)
if self.description == "one_hot":
closest_centres = np.argmin(np.abs(dist), axis=0)
firingrate = np.eye(self.n)[closest_centres].T
if self.description == "top_hat":
firingrate = 1 * (dist < self.widths)
firingrate = (
firingrate * (self.max_fr - self.min_fr) + self.min_fr
) # scales from being between [0,1] to [min_fr, max_fr]
return firingrate
def plot_place_cell_locations(
self,
fig=None,
ax=None,
autosave=None,
):
"""Scatter plots where the centre of the place cells are
Args:
fig, ax: if provided, will plot fig and ax onto these instead of making new.
autosave (bool, optional): if True, will try to save the figure into `ratinabox.figure_directory`.Defaults to None in which case looks for global constant ratinabox.autosave_plots
Returns:
_type_: _description_
"""
if fig is None and ax is None:
fig, ax = self.Agent.Environment.plot_environment(autosave=False)
else:
_, _ = self.Agent.Environment.plot_environment(
fig=fig, ax=ax, autosave=False
)
place_cell_centres = self.place_cell_centres
x = place_cell_centres[:, 0]
if self.Agent.Environment.dimensionality == "1D":
y = np.zeros_like(x)