forked from RatInABox-Lab/RatInABox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Neurons.py
1657 lines (1426 loc) · 72.6 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 numpy as np
import matplotlib
from matplotlib import pyplot as plt
import scipy
from scipy import stats as stats
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 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()
• VelocityCells()
• HeadDirectionCells()
• SpeedCells()
• FeedForwardLayer()
The unique function in each child classes is get_state(). Whenever Neurons.update() is called Neurons.get_state() is then called to calculate and returns 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):
def __init__(self,
Agent,
params={}): #<-- do not change these
default_params = {'a_default_param":3.14159} #note this params dictionary is passed upwards and used in all the parents classes of your class.
default_params.update(params)
self.params = default_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 means 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()
• boundary_vector_preference_function()
default_params = {
"n": 10,
"name": "Neurons",
"color": None, # just for plotting
}
"""
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:
params (dict, optional). Defaults to {}.
Typically you will not actually initialise a Neurons() class, instead you will initialised by one of it's subclasses.
"""
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,
"save_history": True, # whether to save history (set to False if you don't intend to acess Neuron.history for data after)
}
self.Agent = Agent
default_params.update(params)
self.params = default_params
utils.update_class_params(self, self.params)
self.firingrate = np.zeros(self.n)
self.noise = np.zeros(self.n)
self.history = {}
self.history["t"] = []
self.history["firingrate"] = []
self.history["spikes"] = []
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()."
)
def update(self):
# 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()
self.firingrate = firingrate.reshape(-1)
self.firingrate = self.firingrate + self.noise
if self.save_history == True:
self.save_to_history()
return
def plot_rate_timeseries(
self,
t_start=None,
t_end=None,
chosen_neurons="all",
spikes=True,
imshow=False,
fig=None,
ax=None,
xlim=None,
background_color=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 True.
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)
• fig, ax: the figure, axis to plot on (can be None)
xlim: fix xlim of plot irrespective of how much time you're plotting
• background_color: color of the background if not matplotlib default (probably white)
• kwargs sent to mountain plot function, you can ignore these
Returns:
fig, ax
"""
t = np.array(self.history["t"])
# times to plot
if t_start is None:
t_start = t[0]
if t_end is None:
t_end = t[-1]
startid = np.argmin(np.abs(t - (t_start)))
endid = np.argmin(np.abs(t - (t_end)))
rate_timeseries = np.array(self.history["firingrate"][startid:endid])
spike_data = np.array(self.history["spikes"][startid:endid])
t = t[startid:endid]
# neurons to plot
chosen_neurons = self.return_list_of_neurons(chosen_neurons)
spike_data = spike_data[startid:endid, chosen_neurons]
rate_timeseries = rate_timeseries[:, chosen_neurons]
if imshow == False:
firingrates = rate_timeseries.T
fig, ax = utils.mountain_plot(
X=t / 60,
NbyX=firingrates,
color=self.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 or "C1"),
alpha=0.5,
s=5,
linewidth=0,
)
ax.set_xlim(left=t_start / 60, right=t_end / 60)
ax.set_xticks([t_start / 60, t_end / 60])
ax.set_xticklabels([round(t_start / 60, 2), round(t_end / 60, 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=(8, 4))
data = rate_timeseries.T
ax.imshow(data[::-1], aspect=0.3 * data.shape[1] / data.shape[0])
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([0 - 0.5, len(t) + 0.5])
ax.set_xticklabels([round(t_start / 60, 2), round(t_end / 60, 2)])
ax.set_yticks([])
ax.set_ylabel("Neurons")
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,
**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": which method to use. If "analytic" (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 "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.
• 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 multiplanlle 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
• 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
"""
# GET DATA
if method == "groundtruth":
try:
rate_maps = self.get_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, or it does not have an groundtruth receptive field. 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:
t = np.array(self.history["t"])
# times to plot
if len(t) == 0:
print(
"Can't plot rate map by method='history' since there is no available data to plot. "
)
return
t_end = t_end or t[-1]
startid = np.argmin(np.abs(t - (t_start)))
endid = np.argmin(np.abs(t - (t_end)))
pos = np.array(self.Agent.history["pos"])[startid:endid]
t = t[startid:endid]
if method == "history":
rate_timeseries = np.array(self.history["firingrate"])[startid:endid].T
if len(rate_timeseries) == 0:
print("No historical data with which to calculate ratemap.")
if spikes == True:
spike_data = np.array(self.history["spikes"])[startid:endid].T
if len(spike_data) == 0:
print("No historical data with which to plot spikes.")
if self.color == None:
coloralpha = None
else:
coloralpha = list(matplotlib.colors.to_rgba(self.color))
coloralpha[-1] = 0.5
chosen_neurons = self.return_list_of_neurons(chosen_neurons=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 = 1, len(chosen_neurons)
else:
Nx, Ny = shape[0], shape[1]
fig = plt.figure(figsize=(2 * Ny, 2 * Nx))
if colorbar == True and (method in ["groundtruth", "history"]):
cbar_mode = "single"
else:
cbar_mode = None
axes = ImageGrid(
fig,
# (0, 0, 3, 3),
111,
nrows_ncols=(Nx, Ny),
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_)
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"]:
for (i, ax_) in enumerate(axes):
ex = self.Agent.Environment.extent
if method == "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)
elif method == "history":
rate_timeseries_ = rate_timeseries[chosen_neurons[i], :]
rate_map = utils.bin_data_for_histogramming(
data=pos, extent=ex, dx=0.05, weights=rate_timeseries_
)
im = ax_.imshow(
rate_map,
extent=ex,
interpolation="bicubic",
zorder=1,
)
ims.append(im)
vmin, vmax = (
min(vmin, np.min(rate_map)),
max(vmax, np.max(rate_map)),
)
for im in ims:
im.set_clim((vmin, vmax))
if colorbar == True:
cbar = plt.colorbar(ims[-1], cax=cax)
lim_v = vmax if vmax > -vmin else vmin
cbar.set_ticks([0, lim_v])
cbar.set_ticklabels([0, round(lim_v, 1)])
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=2,
linewidth=0,
alpha=0.7,
)
return fig, axes
# PLOT 1D
if self.Agent.Environment.dimensionality == "1D":
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
pos_ = pos[:, 0]
rate_maps = []
for neuron_id in chosen_neurons:
rate_map, x = utils.bin_data_for_histogramming(
data=pos_,
extent=ex,
dx=0.01,
weights=rate_timeseries[neuron_id, :],
)
x, rate_map = utils.interpolate_and_smooth(x, rate_map, sigma=0.03)
rate_maps.append(rate_map)
rate_maps = np.array(rate_maps)
if fig is None and ax is None:
fig, ax = self.Agent.Environment.plot_environment(
height=0.5 * len(chosen_neurons)
)
if method != "neither":
fig, ax = utils.mountain_plot(
X=x, NbyX=rate_maps, color=self.color, fig=fig, ax=ax, **kwargs
)
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=(self.color or "C1"),
alpha=0.5,
s=2,
linewidth=0,
)
ax.set_xlabel("Position / m")
ax.set_ylabel("Neurons")
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(list(self.firingrate))
self.history["spikes"].append(list(cell_spikes))
def animate_rate_timeseries(
self,
t_start=None,
t_end=None,
chosen_neurons="all",
fps=15,
speed_up=1,
**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,
**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,
**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),
)
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, 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, 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
"""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",
}
"""
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 {}.
"""
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",
}
self.Agent = Agent
default_params.update(params)
self.params = default_params
super().__init__(Agent, self.params)
if self.place_cell_centres is None:
self.place_cell_centres = self.Agent.Environment.sample_positions(
n=self.n, method="uniform_jitter"
)
elif type(self.place_cell_centres) is str:
if self.place_cell_centres in ["random", "uniform", "uniform_jitter"]:
self.place_cell_centres = self.Agent.Environment.sample_positions(
n=self.n, method=self.place_cell_centres
)
else:
self.n = self.place_cell_centres.shape[0]
self.place_cell_widths = self.widths * np.ones(self.n)
# 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 enivoronments with 1 additional wall (4 boundaing 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):
"""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.
Returns:
_type_: _description_
"""
if fig is None and ax is None:
fig, ax = self.Agent.Environment.plot_environment()
else:
_, _ = self.Agent.Environment.plot_environment(fig=fig, ax=ax)
place_cell_centres = self.place_cell_centres
ax.scatter(
place_cell_centres[:, 0],
place_cell_centres[:, 1],
c="C1",
marker="x",
s=15,
zorder=2,
)
return fig, ax
class GridCells(Neurons):
"""The GridCells class defines a population of GridCells. This class is a subclass of Neurons() and inherits it properties/plotting functions.
Must be initialised with an Agent and a 'params' dictionary.
GridCells defines a set of 'n' grid cells with random orientations, grid scales and offsets (these can be set non-randomly of coursse). Grids are modelled as the rectified sum of three cosine waves at 60 degrees to each other.
List of functions:
• get_state()
default_params = {
"n": 10,
"gridscale": 0.45,
"random_orientations": True,
"random_gridscales": True,
"random_phase_offsets": True,
"min_fr": 0,
"max_fr": 1,
"name": "GridCells",
}
"""
def __init__(self, Agent, params={}):
"""Initialise GridCells(), 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 {}."""
default_params = {
"n": 10,
"gridscale": 0.45,
"random_orientations": True,
"random_gridscales": True,
"random_phase_offsets": True,
"min_fr": 0,
"max_fr": 1,
"name": "GridCells",
}
self.Agent = Agent
default_params.update(params)
self.params = default_params
super().__init__(Agent, self.params)
# Initialise grid cells
assert (
self.Agent.Environment.dimensionality == "2D"
), "grid cells only available in 2D"
if self.random_phase_offsets == True:
self.phase_offsets = np.random.uniform(0, self.gridscale, size=(self.n, 2))
else:
self.phase_offsets = self.set_phase_offsets()
w = []
for i in range(self.n):
w1 = np.array([1, 0])
if self.random_orientations == True:
w1 = utils.rotate(w1, np.random.uniform(0, 2 * np.pi))
w2 = utils.rotate(w1, np.pi / 3)
w3 = utils.rotate(w1, 2 * np.pi / 3)
w.append(np.array([w1, w2, w3]))
self.w = np.array(w)
if self.random_gridscales == True:
self.gridscales = np.random.rayleigh(scale=self.gridscale, size=self.n)
else:
self.gridscales = np.full(self.n, fill_value=self.gridscale)
if ratinabox.verbose is True:
print(
"GridCells successfully initialised. You can also manually set their gridscale (GridCells.gridscales), offsets (GridCells.phase_offset) and orientations (GridCells.w1, GridCells.w2,GridCells.w3 give the cosine vectors)"
)
return
def get_state(self, evaluate_at="agent", **kwargs):
"""Returns the firing rate of the grid cells.
By default position is taken from the Agent and used to calculate firing rates. This can also by passed directly (evaluate_at=None, pos=pass_array_of_positions) or you 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)
pos = pos.reshape(-1, pos.shape[-1])
# grid cells are modelled as the thresholded sum of three cosines all at 60 degree offsets
# vectors to grids cells "centred" at their (random) phase offsets
vecs = utils.get_vectors_between(
self.phase_offsets, pos
) # shape = (N_cells,N_pos,2)
w1 = np.tile(np.expand_dims(self.w[:, 0, :], axis=1), reps=(1, pos.shape[0], 1))
w2 = np.tile(np.expand_dims(self.w[:, 1, :], axis=1), reps=(1, pos.shape[0], 1))
w3 = np.tile(np.expand_dims(self.w[:, 2, :], axis=1), reps=(1, pos.shape[0], 1))
gridscales = np.tile(
np.expand_dims(self.gridscales, axis=1), reps=(1, pos.shape[0])
)
phi_1 = ((2 * np.pi) / gridscales) * (vecs * w1).sum(axis=-1)
phi_2 = ((2 * np.pi) / gridscales) * (vecs * w2).sum(axis=-1)
phi_3 = ((2 * np.pi) / gridscales) * (vecs * w3).sum(axis=-1)
firingrate = (1 / 3) * ((np.cos(phi_1) + np.cos(phi_2) + np.cos(phi_3)))
firingrate[firingrate < 0] = 0
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 set_phase_offsets(self):
"""Set non-random phase_offsets. Most offsets (cell number: x*y) are grid-like, while the remainings (cell number: n - x*y) are random."""
n_x = int(np.sqrt(self.n))
n_y = self.n // n_x
n_remaining = self.n - n_x * n_y
dx = self.gridscale / n_x
dy = self.gridscale / n_y
grid = np.mgrid[
(0 + dx / 2) : (self.gridscale - dx / 2) : (n_x * 1j),
(0 + dy / 2) : (self.gridscale - dy / 2) : (n_y * 1j),
]
grid = grid.reshape(2, -1).T
remaining = np.random.uniform(0, self.gridscale, size=(n_remaining, 2))
all_offsets = np.vstack([grid, remaining])
return all_offsets
class BoundaryVectorCells(Neurons):
"""The BoundaryVectorCells class defines a population of Boundary Vector Cells. This class is a subclass of Neurons() and inherits it properties/plotting functions.
Must be initialised with an Agent and a 'params' dictionary.
BoundaryVectorCells defines a set of 'n' BVCs cells with random orientations preferences, distance preferences (these can be set non-randomly of course). We use the model described firstly by Hartley et al. (2000) and more recently de Cothi and Barry (2000).
BVCs can have allocentric (mec,subiculum) OR egocentric (ppc, retrosplenial cortex) reference frames.
List of functions:
• get_state()
• boundary_vector_preference_function()
default_params = {
"n": 10,
"reference_frame": "allocentric",
"pref_wall_dist": 0.15,
"angle_spread_degrees": 11.25,
"xi": 0.08, # as in de cothi and barry 2020
"beta": 12,
"dtheta":2, #angular resolution in degrees
"min_fr": 0,
"max_fr": 1,
"name": "BoundaryVectorCells",
}
"""
def __init__(self, Agent, params={}):
"""Initialise BoundaryVectorCells(), 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 {}."""
default_params = {
"n": 10,
"reference_frame": "allocentric",
"pref_wall_dist": 0.15,
"angle_spread_degrees": 11.25,
"xi": 0.08,
"beta": 12,
"dtheta": 2,
"min_fr": 0,
"max_fr": 1,
"name": "BoundaryVectorCells",
}
self.Agent = Agent
default_params.update(params)
self.params = default_params
super().__init__(Agent, self.params)
assert (
self.Agent.Environment.dimensionality == "2D"
), "boundary cells only possible in 2D"
assert (
self.Agent.Environment.boundary_conditions == "solid"
), "boundary cells only possible with solid boundary conditions"
xi = self.xi
beta = self.beta
test_direction = np.array([1, 0])
test_directions = [test_direction]
test_angles = [0]
# numerically discretise over 360 degrees
self.n_test_angles = int(360 / self.dtheta)
for i in range(self.n_test_angles - 1):
test_direction_ = utils.rotate(
test_direction, 2 * np.pi * i * self.dtheta / 360
)
test_directions.append(test_direction_)
test_angles.append(2 * np.pi * i * self.dtheta / 360)
self.test_directions = np.array(test_directions)
self.test_angles = np.array(test_angles)
self.sigma_angles = np.array(
[(self.angle_spread_degrees / 360) * 2 * np.pi] * self.n
)
self.tuning_angles = np.random.uniform(0, 2 * np.pi, size=self.n)
self.tuning_distances = np.random.rayleigh(
scale=self.pref_wall_dist,
size=self.n,
)
self.sigma_distances = self.tuning_distances / beta + xi
# calculate normalising constants for BVS firing rates in the current environment. Any extra walls you add from here onwards you add will likely push the firingrate up further.
locs = self.Agent.Environment.discretise_environment(dx=0.04)
locs = locs.reshape(-1, locs.shape[-1])
self.cell_fr_norm = np.ones(self.n)
self.cell_fr_norm = np.max(self.get_state(evaluate_at=None, pos=locs), axis=1)
if ratinabox.verbose is True:
print(
"BoundaryVectorCells (BVCs) successfully initialised. You can also manually set their orientation preferences (BVCs.tuning_angles, BVCs.sigma_angles), distance preferences (BVCs.tuning_distances, BVCs.sigma_distances)."
)
return
def get_state(self, evaluate_at="agent", **kwargs):
"""Here we implement the same type if boundary vector cells as de Cothi et al. (2020), who follow Barry & Burgess, (2007). See equations there.
The way we do this is a little complex. We will describe how it works from a single position (but remember this can be called in a vectorised manner from an array of positons in parallel)
1. An array of normalised "test vectors" span, in all directions at small increments, from the current position
2. These define an array of line segments stretching from [pos, pos+test vector]
3. Where these line segments collide with all walls in the environment is established, this uses the function "utils.vector_intercepts()"
4. This pays attention to only consider the first (closest) wall forawrd along a line segment. Walls behind other walls are "shaded" by closer walls. Its a little complex to do this and requires the function "boundary_vector_preference_function()"
5. Now that, for every test direction, the closest wall is established it is simple a process of finding the response of the neuron to that wall at that angle (multiple of two gaussians, see de Cothi (2020)) and then summing over all the test angles.
We also apply a check in the middle to utils.rotate the reference frame into that of the head direction of the agent iff self.reference_frame='egocentric'.
By default position is taken from the Agent and used to calculate firing 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").
"""
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)
N_cells = self.n
pos = pos.reshape(-1, pos.shape[-1]) # (N_pos,2)
N_pos = pos.shape[0]
N_test = self.test_angles.shape[0]
pos_line_segments = np.tile(
np.expand_dims(np.expand_dims(pos, axis=1), axis=1), reps=(1, N_test, 2, 1)
) # (N_pos,N_test,2,2)
test_directions_tiled = np.tile(
np.expand_dims(self.test_directions, axis=0), reps=(N_pos, 1, 1)
) # (N_pos,N_test,2)
pos_line_segments[:, :, 1, :] += test_directions_tiled # (N_pos,N_test,2,2)
pos_line_segments = pos_line_segments.reshape(-1, 2, 2) # (N_pos x N_test,2,2)
walls = self.Agent.Environment.walls # (N_walls,2,2)
N_walls = walls.shape[0]
pos_lineseg_wall_intercepts = utils.vector_intercepts(
pos_line_segments, walls
) # (N_pos x N_test,N_walls,2)
pos_lineseg_wall_intercepts = pos_lineseg_wall_intercepts.reshape(
(N_pos, N_test, N_walls, 2)
) # (N_pos,N_test,N_walls,2)
dist_to_walls = pos_lineseg_wall_intercepts[
:, :, :, 0
] # (N_pos,N_test,N_walls)