Repository navigation
Expand file tree
/
Copy pathnetwork.py
More file actions
1948 lines (1526 loc) · 65.9 KB
/
Copy pathnetwork.py
File metadata and controls
1948 lines (1526 loc) · 65.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# encoding: utf-8
import importlib
import itertools as it
import pylab as p
import numpy as np
import logging
import sys
import os
from . import conversion as conv
from . import cutils
from . import db
from . import gather_data
from . import io
from . import meta
from . import pynn_patches
from . import samplers
from . import utils
from .logcfg import log
@meta.HasDependencies
class BoltzmannMachineBase(object):
"""
A set of samplers connected as Boltzmann machine.
"""
def __init__(self, num_samplers, sim_name="pyNN.nest",
sampler_config=None, sampler_kwargs={"silent": True}):
"""
Sets up a Boltzmann network.
sampler_config:
Either one or a list of size `num_samplers` of
SamplerConfiguration objects with which the samplers are
initialized.
sampler_kwargs:
Either a dictionary of additional kwargs supplied to the
samplers or a list of dictionaries to supply each sampler its
own set of kwargs.
"""
log.info("Creating new {} with {} samplers.".format(
self.__class__.__name__, num_samplers))
self.sim_name = sim_name
self.num_samplers = num_samplers
self.population = None
self.projections = None
self.auto_sync_biases = True
if sampler_config is None:
raise ValueError("Did not specify sampler parameters.")
if isinstance(sampler_config, db.SamplerConfiguration):
sampler_config = [sampler_config]\
* self.num_samplers
if isinstance(sampler_kwargs, dict):
sampler_kwargs = it.repeat(sampler_kwargs)
self.samplers = [samplers.LIFsampler(npc, **kwargs) for npc, kwargs
in it.izip(sampler_config, sampler_kwargs)]
if not all(s.tso_parameters is self.samplers[0].tso_parameters
for s in self.samplers):
raise ValueError("currently we only support a single TSO "
"configuration among all samplers")
# unfortunately, tso_params was used before and we need to stay
# backwards-compatible :(
self.tso_params = self.samplers[0].tso_parameters
self.weights_theo = 0.
# biases are set to zero automaticcaly by the samplers
self.saturating_synapses_enabled = False
self.use_proper_tso = True
self.delays = 0.1
######################
# regular attributes #
######################
@meta.DependsOn()
def sim_name(self, name):
"""
The full simulator name.
"""
if not name.startswith("pyNN."):
name = "pyNN." + name
return name
@meta.DependsOn("weights_bio")
def weights_theo(self, weights=None):
"""
Set or retrieve the connection weights
Can be a scalar to set all weights to the same value.
Automatic conversion:
After the weights have been set in either biological or theoretical
units both can be retrieved and the conversion will be done when
needed.
"""
if weights is not None:
# setter part
return self._check_weight_matrix(weights)
else:
# getter part
return self.convert_weights_bio_to_theo(self.weights_bio)
@meta.DependsOn("weights_theo")
def weights_bio(self, weights=None):
"""
Set or retrieve the connection weights
Can be a scalar to set all weights to the same value.
Automatic conversion:
After the weights have been set in either biological or theoretical
units both can be retrieved and the conversion will be done when
needed.
"""
if weights is not None:
# setter part
return self._check_weight_matrix(weights)
else:
# getter part
return self.convert_weights_theo_to_bio(self.weights_theo)
@meta.DependsOn()
def saturating_synapses_enabled(self, value):
"""
Use TSO to model saturating synapses between neurons.
"""
assert isinstance(value, bool)
return value
@meta.DependsOn("biases_bio")
def biases_theo(self, biases=None):
"""
Always set AS A WHOLE array, do not modify the bias-array in-place!
"""
if biases is None:
# getter
return np.array([s.bias_theo for s in self.samplers])
else:
# setter
if not utils.check_list_array(biases):
biases = it.repeat(biases)
for b, sampler in it.izip(biases, self.samplers):
sampler.bias_theo = b
if self.is_created and self.auto_sync_biases:
self.sync_biases_to_pynn()
@meta.DependsOn("biases_theo")
def biases_bio(self, biases=None):
"""
Always set AS A WHOLE array, do not modify the bias-array in-place!
"""
if biases is None:
# getter
return np.array([s.bias_bio for s in self.samplers])
else:
# setter
if not utils.check_list_array(biases):
biases = it.repeat(biases)
for b, sampler in it.izip(biases, self.samplers):
sampler.bias_bio = b
if self.is_created and self.auto_sync_biases:
self.sync_biases_to_pynn()
@meta.DependsOn("biases_theo", "biases_bio")
def v_rests(self):
return np.array([s.get_v_rest_from_bias() for s in self.samplers])
def convert_weights_bio_to_theo(self, weights):
conv_weights = np.zeros_like(weights)
# the column index denotes the target neuron, hence we convert there
for j, sampler in enumerate(self.samplers):
conv_weights[:, j] = sampler.convert_weights_bio_to_theo(
weights[:, j])
return conv_weights
def convert_weights_theo_to_bio(self, weights):
conv_weights = np.zeros_like(weights)
# the column index denotes the target neuron, hence we convert there
for j, sampler in enumerate(self.samplers):
conv_weights[:, j] = sampler.convert_weights_theo_to_bio(
weights[:, j])
return conv_weights
@meta.DependsOn()
def delays(self, delays):
"""
Delays can either be a scalar to indicate a global delay or an
array to indicate the delays between the samplers.
"""
if self.is_created:
log.warn("A PyNN object was already created. Its delays will not "
"be modified!")
delays = self._check_delays(delays)
return delays
@meta.DependsOn()
def tau_refracs(self):
"""
Collects all tau_refracs from all samplers.
Note: Assumes they do not change over the course of simulation!
"""
return np.array([s.neuron_parameters.tau_refrac_calibration
for s in self.samplers])
@meta.DependsOn()
def tso_params(self, params=None):
"""
Specify custom TSO parameters.
(Taken from NEST source doctstrings:)
U double - probability of release increment (U1) [0,1],
default=0.5
u double - Maximum probability of release (U_se) [0,1],
default=0.5
x double - current scaling factor of the weight,
default=U
tau_rec double - time constant for depression in ms,
default=800 ms
tau_fac double - time constant for facilitation in ms,
default=0 (off)
"""
if params is None:
return db.TsoParameters()
else:
if isinstance(params, db.TsoParameters):
return params
elif isinstance(params, dict):
return db.TsoParameters(**params)
else:
raise ValueError("Invalid TSO parameters supplied")
@meta.DependsOn()
def all_samplers_same_model(self):
"""
Returns true of all samplers have the same pynn model.
If this returns False, expect `self.population` to be a list of
size-1 populations unless specified differently during creation.
Note: This gets only calculated once! Don't change self.samplers
afterwards!
"""
return all(isinstance(sampler.neuron_parameters,
type(self.samplers[0].neuron_parameters))
for sampler in self.samplers)
@property
def is_created(self):
return self.population is not None
################
# PYNN methods #
################
def create_no_return(self, sim_setup_kwargs=None, *args, **kwargs):
"""
Runs self.create(*args, **kwargs) but does not return the created
PyNN objects.
This is only useful when wrapping the class in another subprocess.
If sim_setup_kwargs is not None, the dictionary will be used to
setup PyNN.
"""
if sim_setup_kwargs is not None:
sim = importlib.import_module(self.sim_name)
sim.setup(**sim_setup_kwargs)
self.create(*args, **kwargs)
def create(self, **kwargs):
"""
Create the sampling network and return the pynn object.
If population is not None it should have length
`self.num_samplers`. Also, if you specify different samplers to
have different pynn_models, make sure that the list of pynn_objects
provided supports those!
Returns the newly created or specified popluation object for the
samplers and a dictionary over the projections.
`_nest_optimization`: If True the network will try to use as few
sources as possible with the nest specific `poisson_generator`
type.
If a different source model should be used, it can be specified via
_nest_source_model (string) and the corresponding kwargs. If the
source model needs a parrot neuron that repeats its spikes in order
to function, please note it.
"""
log.info("Creating samplers.")
self.population = self.create_population(**kwargs)
log.info("Connecting samplers.")
self.projections = self.create_connectivity(**kwargs)
return self.population, self.projections
def create_population(self, duration=None, _nest_optimization=True,
**kwargs):
assert duration is not None, "Duration must be set!"
sim = importlib.import_module(self.sim_name)
self.sim = sim
assert self.all_samplers_same_model,\
"The samplers have different pynn_models."
# only perform nest optimizations when we have nest as simulator and
# the user requests it
_nest_optimization = _nest_optimization and hasattr(sim, "nest")
log.info("Setting up population for duration: {}ms".format(duration))
if not self.samplers[0].is_using_nest_model(sim):
log.info("PyNN-model: {}".format(self.samplers[0].pynn_model))
else:
log.info("NEST specific model: {}".format(
self.samplers[0].neuron_parameters.nest_model))
population = sim.Population(
self.num_samplers,
self.samplers[0].get_pynn_model_object(sim)())
for i, sampler in enumerate(self.samplers):
local_pop = population[i:i+1]
# if we are performing nest optimizations, the sources will be
# created afterwards
sampler.create(
duration=duration, population=local_pop,
create_pynn_sources=False)
self._set_network_in_samplers(population)
# check whether we have the same source configuration for everything
self._pynn_sources = db.sources_create_connect(
sim,
self.samplers,
duration=duration,
nest_optimized=_nest_optimization)
return population
def create_connectivity(self, **kwargs):
"""
The Base-class does not impose any connectivity.
NOTE: This method should return an object containing all created
projections.
"""
pass
####################
# INTERNAL methods #
####################
def sync_biases_to_pynn(self):
if self.all_samplers_same_model:
if getattr(self.samplers[0].neuron_parameters,
"is_nest_native",
False):
self.population.set(E_L=self.v_rests)
else:
self.population.set(v_rest=self.v_rests)
else:
for s in self.samplers:
s.sync_bias_to_pynn()
def _check_weight_matrix(self, weights):
weights = np.array(weights)
if len(weights.shape) == 0:
scalar_weight = weights
weights = np.empty((self.num_samplers, self.num_samplers))
weights.fill(scalar_weight)
expected_shape = (self.num_samplers, self.num_samplers)
assert weights.shape == expected_shape,\
"Weight matrix shape {}, expected {}".format(
weights.shape, expected_shape)
weights = utils.fill_diagonal(weights, 0.)
return weights
def _check_delays(self, delays):
delays = np.array(delays)
if len(delays.shape) == 0:
scalar_delay = delays
delays = np.empty((self.num_samplers, self.num_samplers))
delays.fill(scalar_delay)
return delays
def _set_network_in_samplers(self, population):
for i, s in enumerate(self.samplers):
s.network["population"] = population
s.network["index"] = i
@meta.HasDependencies
class ThoroughBM(BoltzmannMachineBase):
"""
A BoltzmannMachine focused on getting thorough representations of
probability distributions.
"""
def __init__(self, *args, **kwargs):
super(ThoroughBM, self).__init__(*args, **kwargs)
self.selected_sampler_idx = range(self.num_samplers)
################
# PyNN methods #
################
def create_connectivity(self, **kwargs):
sim = None
sim = importlib.import_module(self.sim_name)
_nest_optimization = (kwargs.get("_nest_optimization", True) and
hasattr(sim, "nest"))
# we dont set any connections for weights that are == 0.
weight_is = {}
weight_is["exc"] = self.weights_bio > 0.
weight_is["inh"] = self.weights_bio < 0.
receptor_type = {"exc": "excitatory", "inh": "inhibitory"}
global_delay = len(self.delays.shape) == 0
column_names = ["weight", "delay"]
tau_rec_overwritten = self.tso_params.tau_rec is not None
if self.saturating_synapses_enabled:
log.info("Creating saturating synapses.")
if not tau_rec_overwritten:
column_names.append("tau_rec")
tau_rec = []
for sampler in self.samplers:
tau_rec.append({
"exc": sampler.neuron_parameters.tau_syn_E,
"inh": sampler.neuron_parameters.tau_syn_I,
})
else:
log.info("TSO: tau_rec overwritten.")
else:
log.info("Creating non-saturating synapses.")
projections = {}
for wt in ["exc", "inh"]:
if weight_is[wt].sum() == 0:
# there are no weights of the current type, continue
continue
log.info("Connecting {} weights.".format(receptor_type[wt]))
weights = self.weights_bio.copy()
if self.saturating_synapses_enabled:
weights *= self.tso_params.weight_rescale
if wt == "inh":
weights *= (np.array([("_curr_" in s.pynn_model)
for s in self.samplers], dtype=int) * 2) - 1
if self.saturating_synapses_enabled and _nest_optimization\
and self.use_proper_tso:
# using native nest synapse model, we need to take care of
# weight transformations ourselves
weights *= 1000.
connection_list = []
for i_pre, i_post in it.izip(*np.nonzero(weight_is[wt])):
connection = (i_pre, i_post, weights[i_pre, i_post],
self.delays if global_delay
else self.delays[i_pre, i_post])
if self.saturating_synapses_enabled and\
not tau_rec_overwritten:
connection += (tau_rec[i_post][wt],)
connection_list.append(connection)
if self.saturating_synapses_enabled:
if not _nest_optimization or not self.use_proper_tso:
tso_params = self.tso_params.get_dict()
# delete all keys that are not parameters of the pyNN
# synapse
del tso_params["u"]
del tso_params["x"]
del tso_params["weight_rescale"]
synapse_type = self.sim.TsodyksMarkramSynapse(weight=0.,
**tso_params)
else:
log.info("Using 'tsodyks2_synapse' native synapse model.")
pynn_patches.fix_nest_tsodyks(
"avoid_pynn_trying_to_be_smart")
tso_dikt = utils.filter_dict(self.tso_params.get_dict(),
lambda _, v: v is not None)
# weight rescaling is something we do manually, it is not
# a parameter of the synapse type -> delete
del tso_dikt["weight_rescale"]
pynn_patches.fix_nest_synapse_defaults(
"avoid_pynn_trying_to_be_smart")
synapse_type = sim.native_synapse_type(
"avoid_pynn_trying_to_be_smart")(**tso_dikt)
else:
synapse_type = sim.StaticSynapse(weight=0.)
projections[wt] = sim.Projection(
self.population, self.population,
synapse_type=synapse_type,
connector=sim.FromListConnector(connection_list,
column_names=column_names),
receptor_type=receptor_type[wt])
return projections
#########################
# gather spikes methods #
#########################
# methods to gather data
@meta.DependsOn()
def spike_data(self, spike_data=None):
"""
The spike data from which to compute distributions.
"""
if spike_data is not None:
assert "spiketrains" in spike_data
assert "duration" in spike_data
return spike_data
else:
# We are requesting data when there is None
return None
def gather_spikes(self,
duration, dt=0.1, burn_in_time=100., create_kwargs=None,
sim_setup_kwargs=None, initial_vmem=None):
"""
sim_setup_kwargs are the kwargs for the simulator (random seeds).
initial_vmem are the initialized voltages for all samplers.
"""
log.info("Gathering spike data in subprocess..")
self.spike_data = gather_data.gather_network_spikes(
self, duration=duration, dt=dt, burn_in_time=burn_in_time,
create_kwargs=create_kwargs,
sim_setup_kwargs=sim_setup_kwargs,
initial_vmem=initial_vmem)
def get_sample_states(self, time_per_sample=10.):
dt = self.spike_data.get("dt", 0.1)
steps_per_sample = int(time_per_sample / dt)
return cutils.generate_states(
spike_ids=self.selected_sampler_spikes["id"],
spike_times=np.array(self.selected_sampler_spikes["t"] / dt,
dtype=int),
tau_refrac_pss=np.array(
[int(self.samplers[
i].neuron_parameters.tau_refrac_calibration / dt)
for i in self.selected_sampler_idx]),
num_samplers=len(self.selected_sampler_idx),
steps_per_sample=steps_per_sample,
duration=np.array(self.spike_data["duration"] / dt, dtype=int)
)
@meta.DependsOn("spike_data")
def selected_sampler_spikes(self):
log.info("Getting ordered spikes for selected samplers.")
spikes = self.ordered_spikes
selected_idx = np.zeros(spikes.size, dtype=bool)
for idx in self.selected_sampler_idx:
selected_idx += spikes["id"] == idx
spikes = spikes[selected_idx].copy()
new_idx = np.zeros_like(spikes["id"])
for i, idx in enumerate(self.selected_sampler_idx):
new_idx[spikes["id"] == idx] = i
spikes["id"] = new_idx
return spikes
@meta.DependsOn("spike_data")
def ordered_spikes(self):
log.info("Getting ordered spikes")
return utils.get_ordered_spike_idx(self.spike_data["spiketrains"])
@meta.DependsOn()
def selected_sampler_idx(self, selected_sampler_idx=None):
if selected_sampler_idx is None:
return np.arange(self.num_samplers, dtype=np.int)
else:
return np.array(list(set(selected_sampler_idx)), dtype=np.int)
################
# MISC methods #
################
def save(self, filename):
"""
Save the current Boltzmann network in zipped-pickle form.
"""
utils.save_pickle(self, filename)
@classmethod
def load(cls, filename):
"""
Returns successfully loaded boltzmann network or None.
"""
try:
return utils.load_pickle(filename)
except IOError:
if log.getEffectiveLevel() <= logging.DEBUG:
log.debug(sys.exc_info()[0])
return None
#######################
# PROBABILITY methdos #
#######################
@meta.DependsOn("spike_data", "selected_sampler_idx")
def dist_marginal_sim(self):
"""
Marginal distribution computed from spike data.
"""
log.info("Calculating marginal probability distribution for {} "
"samplers.".format(len(self.selected_sampler_idx)))
marginals = np.zeros((len(self.selected_sampler_idx),))
for i, idx in enumerate(self.selected_sampler_idx):
sampler = self.samplers[idx]
spikes = self.spike_data["spiketrains"][idx]
marginals[i] = len(spikes)\
* sampler.neuron_parameters.tau_refrac_calibration
marginals /= self.spike_data["duration"]
return marginals
@meta.DependsOn("spike_data", "selected_sampler_idx")
def dist_joint_sim(self):
# tau_refrac per selected sampler
tau_refrac_pss = np.array(
[self.samplers[i].neuron_parameters.tau_refrac_calibration
for i in self.selected_sampler_idx])
spike_ids = np.require(self.ordered_spikes["id"], requirements=["C"])
spike_times = np.require(self.ordered_spikes["t"], requirements=["C"])
return cutils.get_bm_joint_sim(
spike_ids, spike_times, self.selected_sampler_idx,
tau_refrac_pss, self.spike_data["duration"])
@meta.DependsOn("selected_sampler_idx", "biases_theo", "weights_theo")
def dist_marginal_theo(self):
"""
Marginal distribution
"""
lc_biases = self.biases_theo
lc_weights = self.weights_theo
lc_biases = np.require(lc_biases, requirements=["C"])
lc_weights = np.require(lc_weights, requirements=["C"])
return cutils.get_bm_marginal_theo(
lc_weights, lc_biases, self.selected_sampler_idx)
@meta.DependsOn("selected_sampler_idx", "biases_theo", "weights_theo")
def dist_joint_theo(self):
"""
Joint distribution for all selected samplers.
"""
log.info("Calculating joint theoretical distribution for {} samplers."
.format(len(self.selected_sampler_idx)))
lc_biases = self.biases_theo
lc_weights = self.weights_theo
lc_biases = np.require(lc_biases, requirements=["C"])
lc_weights = np.require(lc_weights, requirements=["C"])
joint = cutils.get_bm_joint_theo(lc_weights, lc_biases)
ssi = self.selected_sampler_idx
if len(ssi) == self.num_samplers\
and np.all(ssi == np.arange(self.num_samplers)):
return joint
else:
for idx in xrange(self.num_samplers):
if idx in self.selected_sampler_idx:
continue
joint = joint.sum(axis=idx, keepdims=True)
return joint.squeeze()
################
# PLOT methods #
################
@meta.plot_function("comparison_dist_marginal")
def plot_dist_marginal(self, logscale=True, fig=None, ax=None):
width = 1./3.
idx = np.arange(self.dist_marginal_theo.size, dtype=np.int)
if logscale:
ax.set_yscale("log")
min_val = min(self.dist_marginal_theo.min(),
self.dist_marginal_sim.min())
# find corresponding exponent
bottom = 10**np.floor(np.log10(min_val))
else:
bottom = 0.
ax.bar(idx, height=self.dist_marginal_theo.flatten(), width=width,
bottom=bottom, color="r", edgecolor="None",
label="marginal theo")
ax.bar(idx+width, height=self.dist_marginal_sim.flatten(), width=width,
bottom=bottom, color="b", edgecolor="None",
label="marginal sim")
ax.legend(loc="best")
ax.set_xlim(0, idx[-1]+2*width)
ax.set_xlabel("sampler index $i$")
ax.set_ylabel("$p_{ON}$(sampler $i$)")
@meta.plot_function("comparison_dist_joint")
def plot_dist_joint(self, logscale=True, fig=None, ax=None):
width = 1./3.
idx = np.arange(self.dist_joint_theo.size, dtype=np.int)
if logscale:
ax.set_yscale("log")
min_val = min(self.dist_joint_theo.min(),
self.dist_joint_sim.min())
# find corresponding exponent
bottom = 10**np.floor(np.log10(min_val))
else:
bottom = 0.
ax.bar(idx, height=self.dist_joint_theo.flatten(), width=width,
bottom=bottom, color="r", edgecolor="None", label="joint theo")
ax.bar(idx+width, height=self.dist_joint_sim.flatten(), width=width,
bottom=bottom, color="b", edgecolor="None", label="joint sim")
ax.legend(loc="best")
ax.set_xlabel("state")
ax.set_ylabel("probability")
ax.set_xlim(0, idx[-1]+2*width)
ax.set_xticks(idx+width)
ax.set_xticklabels(
labels=["\n".join(map(str, state))
for state in np.ndindex(*self.dist_joint_theo.shape)])
@meta.plot_function("weights_theo")
def plot_weights_theo(self, fig=None, ax=None):
self._plot_weights(self.weights_theo, self.biases_theo,
label="theoretical values", fig=fig, ax=ax)
@meta.plot_function("weights_bio")
def plot_weights_bio(self, fig=None, ax=None):
self._plot_weights(self.weights_bio, self.biases_theo,
label="biological values", fig=fig, ax=ax)
####################
# INTERNAL methods #
####################
def _plot_weights(self, weights, biases, label="", cmap="jet", fig=None,
ax=None):
cmap = p.get_cmap(cmap)
matrix = weights.copy()
for i in xrange(matrix.shape[0]):
matrix[i, i] = biases[i]
imshow = ax.imshow(matrix, cmap=cmap, interpolation="nearest")
cbar = fig.colorbar(imshow, ax=ax)
cbar.set_label(label)
ax.set_xlabel("sampler id")
ax.set_ylabel("sampler id")
@meta.HasDependencies
class RapidBMBase(BoltzmannMachineBase):
"""
Rapid version of the regular BoltzmannMachine, intended for usage with
learning algorithms and rapid weight changes.
Currently only the NEST backend is supported.
"""
nest_synapse_type = "cd_connection"
def __init__(self, *args, **kwargs):
super(RapidBMBase, self).__init__(*args, **kwargs)
self._binary_state_set_externally = False
self.sim = None
self.time_current = 0.1
self.eta = 1e-4
# if set this nest synapse type will be used
self.fixed_nest_synapse_name = None
# how many updates do we queue maximally
self.num_max_queued_updates = 100
self.time_sim_step = 30. # ms
self.time_wipe = 50. # time between silence and imprint
self.time_imprint = 30. # how long are the
self._update_num = 0
self._update_info = {
"to_notify": set(),
}
# has to be non-None for the propagation to binary state to work
self.last_spiketimes = np.zeros(self.num_samplers) - 1000.
# shape: (num_factors, 2) first is eta, second is data, third is
# model/recon
self.update_factors = np.zeros((self.num_samplers, 2))
def create_population(self, **kwargs):
"""
(See also: BoltzmannMachineBase.create)
If connectivity_matrix is a boolean array it can be used to specify
which synapses should initially be connected (for learning).
Otherwise the connectivity_matrix is inferred from the current
weight configuration.
"""
sim = importlib.import_module(self.sim_name)
self.sim = sim
assert hasattr(self.sim, "nest"), "Only works with NEST."
# self._ensure_cd_pynn_models()
kwargs["duration"] = self.sim.nest.GetKernelStatus()["T_max"]
population = super(RapidBMBase, self).create_population(**kwargs)
self._sampler_gids = population.all_cells.tolist()
self._last_spiketime_detector_id = self.sim.nest.Create(
"last_spike_detector")
self.sim.nest.Connect(
population.all_cells.tolist(),
self._last_spiketime_detector_id, "all_to_all")
self.population = population
log.info("Creating imprint circuitry…")
self._create_imprint_circuitry()
self.update_samplers()
return population
def create_connectivity(self, **kwargs):
# TODO: Add support for TSO
if self.saturating_synapses_enabled:
log.warn(self.__class__.__name__ + " currently does not support "
"saturating synapses.")
global_delay = len(self.delays.shape) == 0
nest = self.sim.nest
connectivity_matrix = self.weights_bio != 0.
self.connectivity_matrix = connectivity_matrix
gids = self._sampler_gids
self._copy_synapse_type()
for src, tgt in it.izip(*np.where(connectivity_matrix)):
nest.Connect(
gids[src], gids[tgt], syn_spec={
"weight": 0.,
"delay": self.delays[src, tgt] if not global_delay
else self.delays,
"model": self.local_nest_synapse_type})
# we need to sort the returned connections by gids, not by thread
# to stay consistent with the update machinery
self._nest_connections = sorted(
nest.GetConnections(gids, gids),
key=utils.nest_key_connections)
self.create_update_machinery()
def use_same_shared_update_data_as(self, other_bm):
self._update_info["synapse_type_to_copy"] =\
other_bm.local_nest_synapse_type
other_bm._update_info["to_notify"].add(self)
def queue_update(self):
"""
Indicate that the synapses should update in the next run.
"""
if self.update_params.get_snapshots_used()\
>= self.num_max_queued_updates:
self.update_params.clear_updates()
self.update_params.prepare_next_update()
self.update_params.set_eta(self.eta)
self.update_params.set_update_data(self.update_factors)
self.update_params.set_weight_conversion_factors(
[[s.factor_weights_theo_to_bio_exc,
s.factor_weights_theo_to_bio_inh]
for s in self.samplers])
self.update_params.flush_files()
if self.update_params.get_snapshots_used()\
== self.num_max_queued_updates:
to_notify = [self]
try:
while True:
bm = to_notify.pop()
bm.manual_update()
for b in bm._update_info["to_notify"]:
to_notify.append(b)
except IndexError:
pass
def continue_run(self, runtime):
"""
Continue running the network for the specified time without
imprinting/wiping any state.
"""
self.time_current = self.sim.run_for(runtime)
def run(self):
"""
Run the network for self.time_sim_step milliseconds; after that the
binary state can be inspected.
"""
time_till = self.prepare_run()
self.sim.run_until(time_till)
self.process_run()
return self.time_current
def prepare_run(self):
"""
When using several RapidBMBase at the same time, manually
set up a run with this function.
Returns the needed time for which the simulation needs to be run.
Do not forget to call process_run after the run is complete.
Returns the time until which the sim has to be run.
"""