Changeset 186
- Timestamp:
- 01/28/08 17:45:43 (10 months ago)
- Files:
-
- branches/multifile (modified) (1 prop)
- branches/multifile/src/common.py (modified) (16 diffs)
- branches/multifile/src/nest2/__init__.py (modified) (13 diffs)
- branches/multifile/src/nest2/cells.py (modified) (6 diffs)
- branches/multifile/src/nest2/connectors.py (modified) (6 diffs)
- branches/multifile/test (modified) (1 prop)
- branches/multifile/test/nest2tests.py (modified) (9 diffs)
- branches/multifile/test/pcsimtests_lowlevel.py (modified) (1 diff)
- branches/multifile/test/simple_STDP.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
branches/multifile
- Property svn:ignore set to
build
.project
.pydevproject
- Property svn:ignore set to
branches/multifile/src/common.py
r181 r186 11 11 import numpy 12 12 from math import * 13 13 from pyNN import random 14 14 15 15 class InvalidParameterValueError(Exception): pass … … 19 19 20 20 dt = 0.1 21 _min_delay = 0.1 21 22 22 23 # ============================================================================== … … 189 190 190 191 def checkParameters(self, supplied_parameters, with_defaults=False): 191 """Checks that the parameters exist and have values of the correct type.""" 192 """ 193 Returns a parameter dictionary, checking that each 194 supplied_parameter is in the default_parameters and 195 converts to the type of the latter. 196 197 If with_defaults==True, parameters not in 198 supplied_parameters are in the returned dictionary 199 as in default_parameters. 200 201 """ 192 202 default_parameters = self.__class__.default_parameters 193 203 if with_defaults: … … 237 247 return translated_parameters 238 248 249 def update_parameters(self,parameters): 250 """ 251 update self.parameters with those in parameters 252 """ 253 self.parameters.update(self.translate1(parameters, with_defaults=False)) 254 255 239 256 def __init__(self,parameters): 240 257 self.parameters = self.checkParameters(parameters, with_defaults=True) … … 312 329 'i_offset' : 0.0, # Offset current in nA 313 330 'v_init' : -65.0, # Membrane potential in mV at t = 0 331 } 332 333 class IF_cond_exp_sfa_rr(StandardCellType): 334 """Linear leaky integrate and fire model with fixed threshold, 335 decaying-exponential post-synaptic conductance, conductance based spike-frequency adaptation, 336 and a conductance-based relative refractory mechanism. 337 338 See: Muller et al (2007) Spike-frequency adapting neural ensembles: Beyond mean-adaptation 339 and renewal theories. Neural Computation 19: 2958-3010. 340 """ 341 342 default_parameters = { 343 'v_rest' : -65.0, # Resting membrane potential in mV. 344 'cm' : 1.0, # Capacity of the membrane in nF 345 'tau_m' : 20.0, # Membrane time constant in ms. 346 'tau_refrac' : 0.0, # Duration of refractory period in ms. 347 'tau_syn_E' : 5.0, # Decay time of the excitatory synaptic conductance in ms. 348 'tau_syn_I' : 5.0, # Decay time of the inhibitory synaptic conductance in ms. 349 'e_rev_E' : 0.0, # Reversal potential for excitatory input in mV 350 'e_rev_I' : -70.0, # Reversal potential for inhibitory input in mV 351 'v_thresh' : -50.0, # Spike threshold in mV. 352 'v_reset' : -65.0, # Reset potential after a spike in mV. 353 'i_offset' : 0.0, # Offset current in nA 354 'v_init' : -65.0, # Membrane potential in mV at t = 0 355 'tau_sfa' : 100.0, # Time constant of spike-frequency adaptation in ms 356 'e_rev_sfa' : -75.0, # spike-frequency adaptation conductance reversal potential in mV 357 'q_sfa' : 15.0, # Quantal spike-frequency adaptation conductance increase in nS 358 'tau_rr' : 2.0, # Time constant of the relative refractory mechanism in ms 359 'e_rev_rr' : -75.0, # relative refractory mechanism conductance reversal potential in mV 360 'q_rr' : 3000.0 # Quantal relative refractory conductance increase in nS 361 362 } 363 364 365 class IF_facets_hardware1(StandardCellType): 366 """Leaky integrate and fire model with conductance-based synapses and fixed 367 threshold as it is resembled by the FACETS Hardware Stage 1. For further 368 details regarding the hardware model see the FACETS-internal Wiki: 369 https://facets.kip.uni-heidelberg.de/private/wiki/index.php/WP7_NNM 370 """ 371 372 default_parameters = { 373 'cm' : 0.2, # nF 374 'g_leak' : 20.0, # nS 375 'tau_refrac' : 1.0, # ms 376 'tau_syn_E' : 20.0, # ms 377 'tau_syn_I' : 20.0, # ms 378 'v_reset' : -80.0, # mV 379 'e_rev_I' : -75.0, # mV, 380 'v_rest' : -70.0, # mV 381 'v_thresh' : -57.0, # mV 382 'e_rev_E' : 0.0, # mV 314 383 } 315 384 … … 370 439 } 371 440 441 class SpikeSourceInhGamma(StandardCellType): 442 """Spike source, generating realizations of an inhomogeneous gamma process, employing 443 the thinning method. 444 445 See: Muller et al (2007) Spike-frequency adapting neural ensembles: Beyond mean-adaptation 446 and renewal theories. Neural Computation 19: 2958-3010. 447 """ 448 449 default_parameters = { 450 'a' : numpy.array([1.0]),# time histogram of parameter a of a gamma distribution (dimensionaless) 451 'b' : numpy.array([1.0]),# time histogram of parameter b of a gamma distribution (seconds) 452 'tbins' : numpy.array([0]), # time bins of the time histogram of a,b in units of ms 453 'rmax' : 1.0, # Rate (Hz) of the Poisson process to be thinned, usually set to max(1/b) 454 'start' : 0.0, # Start time (ms) 455 'duration' : 1e6 # Duration of spike sequence (ms) 456 } 457 458 459 372 460 class SpikeSourceArray(StandardCellType): 373 461 """Spike source generating spikes at the times given in the spike_times array.""" … … 628 716 return _abstractMethod(self) 629 717 718 719 def getSpikes(self): 720 """ 721 returns a numpy array of the spikes of the population 722 723 Useful for small populations, for example for single neuron Monte-Carlo. 724 725 NOTE: getSpikes or printSpikes should be called only once per run, 726 because they mangle simulator recorder files. 727 """ 728 729 return _abstractMethod(self) 730 630 731 def print_v(self,filename,gather=True, compatible_output=True): 631 732 """ … … 901 1002 902 1003 class Connector(object): 903 """Abstract base class for Connector classes.""" 904 905 def __init__(self): 906 _abstractMethod(self) 1004 """Base class for Connector classes.""" 1005 1006 def __init__(self, weights, delays): 1007 self.w_index = 0 # should probably use a generator 1008 self.d_index = 0 # rather than storing these values 1009 self.weights = weights 1010 self.delays = delays 907 1011 908 1012 def connect(self,projection): 909 1013 """Connect all neurons in ``projection``""" 910 1014 _abstractMethod(self) 911 1015 1016 def getWeights(self, N): 1017 """ 1018 Returns the next N weight values 1019 """ 1020 if isinstance(self.weights, random.RandomDistribution): # random 1021 weights = numpy.array(self.weights.next(N)) 1022 elif isinstance(self.weights, int) or isinstance(self.weights, float): # int, float 1023 weights = numpy.ones((N,))*float(self.weights) 1024 elif hasattr(self.weights, "__len__"): # numpy array 1025 weights = self.weights[self.w_index:self.w_index+N] 1026 else: 1027 raise Exception("weights is of type %s" % type(self.weights)) 1028 assert numpy.all(weights>=0), "Weight values must be positive" 1029 self.w_index += N 1030 return weights 1031 1032 def getDelays(self, N, start=0): 1033 """ 1034 Returns the next N delays values 1035 """ 1036 if isinstance(self.delays, random.RandomDistribution): # random 1037 delays = numpy.array(self.delays.next(N)) 1038 elif isinstance(self.weights, int) or isinstance(self.weights, float): # int, float 1039 delays = numpy.ones((N,))*float(self.delays) 1040 elif hasattr(delays, "__len__"): # numpy array 1041 delays = self.delays[self.d_index:self.d_index+N] 1042 else: 1043 raise Exception("delays is of type %s" % type(self.delays)) 1044 assert numpy.all(delays>=_min_delay), "Delay values must be greater than the minimum delay" 1045 self.d_index += N 1046 return delays 1047 912 1048 class AllToAllConnector(Connector): 913 1049 """ … … 916 1052 """ 917 1053 918 def __init__(self, allow_self_connections=True, weights=None, delays=None): 1054 def __init__(self, allow_self_connections=True, weights=0.0, delays=_min_delay): 1055 Connector.__init__(self, weights, delays) 919 1056 assert isinstance(allow_self_connections, bool) 920 1057 self.allow_self_connections = allow_self_connections 921 self.weights = weights 922 self.delays = delays 923 924 1058 925 1059 class FixedNumberPostConnector(Connector): 926 1060 """ 927 Connects all cells in the presynaptic population to fixed number of 928 cells in the postsynaptic population, randomly choosen. 929 """ 930 def __init__(self, fixedpost, allow_self_connections=True, weights=None, delays=None): 1061 Each postsynaptic cell receives a fixed number of connections, chosen 1062 randomly from the presynaptic cells. 1063 """ 1064 1065 def __init__(self, n, allow_self_connections=True, weights=0.0, delays=_min_delay): 1066 Connector.__init__(self, weights, delays) 931 1067 assert isinstance(allow_self_connections, bool) 932 1068 self.allow_self_connections = allow_self_connections 933 self.weights = weights 934 self.delays = delays 935 self.fixedpost = int(fixedpost) 936 1069 if isinstance(n, int): 1070 self.n = n 1071 assert n >= 0 1072 elif isinstance(n, random.RandomDistribution): 1073 self.rand_distr = n 1074 # weak check that the random distribution is ok 1075 assert numpy.all(numpy.array(n.next(100)) > 0), "the random distribution produces negative numbers" 1076 else: 1077 raise Exception("n must be an integer or a RandomDistribution object") 937 1078 938 1079 class FixedNumberPreConnector(Connector): … … 941 1082 cells in the presynaptic population, randomly choosen. 942 1083 """ 943 def __init__(self, fixedpre, allow_self_connections=True, weights=None, delays=None): 1084 def __init__(self, n, allow_self_connections=True, weights=0.0, delays=_min_delay): 1085 Connector.__init__(self, weights, delays) 944 1086 assert isinstance(allow_self_connections, bool) 945 1087 self.allow_self_connections = allow_self_connections 946 self.weights = weights 947 self.delays = delays 948 self.fixedpre = int(fixedpre) 1088 if isinstance(n, int): 1089 self.n = n 1090 assert n >= 0 1091 elif isinstance(n, random.RandomDistribution): 1092 self.rand_distr = n 1093 # weak check that the random distribution is ok 1094 assert numpy.all(numpy.array(n.next(100)) > 0), "the random distribution produces negative numbers" 1095 else: 1096 raise Exception("n must be an integer or a RandomDistribution object") 949 1097 950 1098 class OneToOneConnector(Connector): … … 959 1107 """ 960 1108 961 def __init__(self, weights=None, delays=None): 962 self.weights = weights 963 self.delays = delays 964 pass 1109 def __init__(self, weights=0.0, delays=None): 1110 Connector.__init__(self, weights, delays) 965 1111 966 1112 class FixedProbabilityConnector(Connector): … … 969 1115 """ 970 1116 971 def __init__(self, p_connect, allow_self_connections=True, weights=None, delays=None): 1117 def __init__(self, p_connect, allow_self_connections=True, weights=0.0, delays=_min_delay): 1118 Connector.__init__(self, weights, delays) 972 1119 assert isinstance(allow_self_connections, bool) 973 1120 self.allow_self_connections = allow_self_connections 974 self.weights = weights975 self.delays = delays976 1121 self.p_connect = float(p_connect) 977 1122 assert 0 <= self.p_connect … … 986 1131 axes='xyz' is the same as axes=None. 987 1132 It may be that the pre and post populations use different units for position, e.g. 988 degrees and µm. In this case, `scale_factor` can be specified, which is applied1133 degrees and õm. In this case, `scale_factor` can be specified, which is applied 989 1134 to the positions in the post-synaptic population. An offset can also be included. 990 1135 """ … … 993 1138 'xy': [0,1], 'yz': [1,2], 'xz': [0,2], 'xyz': None, None: None} 994 1139 995 def __init__(self, d_expression, axes=None, scale_factor=1.0, offset=0., periodic_boundaries=False, allow_self_connections=True, weights=None, delays=None): 1140 def __init__(self, d_expression, axes=None, scale_factor=1.0, offset=0., 1141 periodic_boundaries=False, allow_self_connections=True, 1142 weights=0.0, delays=_min_delay): 1143 Connector.__init__(self, weights, delays) 996 1144 assert isinstance(allow_self_connections, bool) 997 1145 assert isinstance(d_expression, str) … … 1004 1152 self.d_expression = d_expression 1005 1153 self.allow_self_connections = allow_self_connections 1006 self.weights = weights1007 self.delays = delays1008 1154 self.mask = DistanceDependentProbabilityConnector.AXES[axes] 1009 1155 self.periodic_boundaries = periodic_boundaries … … 1012 1158 self.scale_factor = scale_factor 1013 1159 self.offset = offset 1160 1161 1014 1162 1015 1163 # ============================================================================== branches/multifile/src/nest2/__init__.py
r185 r186 4 4 $Id$ 5 5 """ 6 __version__ = "$Rev ision:5$"6 __version__ = "$Rev$" 7 7 8 8 import nest … … 351 351 nest.ConnectWD([src],[tgt],[weight],[delay]) 352 352 connect_id += [Connection(src,tgt)] 353 except nest.SLIError: 353 #except nest.SLIError: 354 except Exception: # unfortunately, SLIError seems to have disappeared.Hopefully it will be reinstated. 354 355 raise common.ConnectionError 355 356 return connect_id … … 447 448 os.remove(nest_filename) 448 449 if gather and len(node_list) > 1: 449 raise Warning("'gather' not currently supported.") 450 nest.sps(recorder[0]) 451 nest.sr("GetStatus /filename get") 452 nest_filename = nest.spp() #nest.GetStatus(recorder, "filename") 450 453 if nest.Rank() == 0: # only on the master node (?) 451 454 for node in node_list: 452 pass # not a good way to do it at the moment 453 455 merged_filename = "%s/%s_%d" % (os.path.dirname(nest_filename), user_filename, node) 456 system_line = 'cat %s >> %s' % (nest_filename, merged_filename) 457 #print system_line 458 os.system(system_line) 459 os.remove(nest_filename) 460 454 461 if compatible_output: 455 462 if gather == False or nest.Rank() == 0: # if we gather, only do this on the master node … … 465 472 ## Writing header info (e.g., dimensions of the population) 466 473 if population is not None: 467 result.write("# " + "\t".join([str(d) for d in population.dim]) + "\n") 474 result.write("# dimensions =" + "\t".join([str(d) for d in population.dim]) + "\n") 475 result.write("# first_id = %d\n" % population.cell[0]) 476 result.write("# last_id = %d\n" % population.cell[-1]) 468 477 padding = population.cell.flatten()[0] 469 478 else: … … 504 513 recorder_dict.pop(user_filename) 505 514 515 def _get(population=None, variable=None): 516 global recorder_dict 517 518 if population is None: 519 recorder = recorder_dict[user_filename] 520 else: 521 assert variable in ['spikes', 'v', 'conductance'] 522 recorder = population.recorders[variable] 523 524 #print "Printing to %s from recorder %s (compatible_output=%s)" % (user_filename, recorder, compatible_output) 525 526 nest.FlushDevice(recorder) 527 status = nest.GetStatus([0])[0] 528 local_num_threads = status['local_num_threads'] 529 node_list = range(nest.GetStatus([0], "num_processes")[0]) 530 531 # Combine data from different threads to the zeroeth thread 532 nest.sps(recorder[0]) 533 nest.sr("%i GetAddress %i append" % (recorder[0], 0)) 534 nest.sr("GetStatus /filename get") 535 base_filename = nest.spp() #nest.GetStatus(recorder, "filename") 536 537 if local_num_threads>1: 538 for nest_thread in range(1,local_num_threads): 539 nest.sps(recorder[0]) 540 nest.sr("%i GetAddress %i append" % (recorder[0], nest_thread)) 541 nest.sr("GetStatus /filename get") 542 nest_filename = nest.spp() #nest.GetStatus(recorder, "filename") 543 system_line = 'cat %s >> %s' % (nest_filename, base_filename) 544 os.system(system_line) 545 os.remove(nest_filename) 546 547 # now we have the merged_filename 548 549 if population is not None: 550 padding = population.cell.flatten()[0] 551 else: 552 padding = 0 553 554 555 data = _readArray(base_filename, sepchar=None) 556 data[:,0] = data[:,0] - padding 557 os.remove(base_filename) 558 559 return data 560 561 506 562 def _readArray(filename, sepchar=None, skipchar='#'): 507 563 logging.debug(filename) … … 625 681 def ids(self): 626 682 return self.__iter__() 627 683 628 684 def locate(self, id): 629 685 """Given an element id in a Population, return the coordinates. … … 656 712 return coords 657 713 714 def index(self, n): 715 """Return the nth cell in the population.""" 716 if hasattr(n, '__len__'): 717 n = numpy.array(n) 718 return self.cell[n] 719 658 720 def set(self,param,val=None): 659 721 """ … … 676 738 if isinstance(self.celltype, common.StandardCellType): 677 739 paramDict = self.celltype.translate1(paramDict) 678 nest.SetStatus(numpy.reshape(self.cell,(self.size,)), [paramDict]) 679 740 nest.SetStatus(self.cell_local, [paramDict]) 680 741 681 742 def tset(self,parametername,valueArray): … … 702 763 val = list(val) # tuples, arrays are all converted to lists, since this is what SpikeSourceArray expects. This is not very robust though - we might want to add things that do accept arrays. 703 764 else: 704 nest.SetStatus([cell],[{parametername: val}]) 705 except nest.SLIError: 765 if cell in self.cell_local: 766 nest.SetStatus([cell],[{parametername: val}]) 767 #except nest.SLIError: 768 except Exception: # unfortunately, SLIError seems to have disappeared. 706 769 raise common.InvalidParameterValueError, "Error from SLI" 707 770 else: … … 720 783 else: 721 784 rarr = rand_distr.next(n=self.size) 722 cells = numpy.reshape(self.cell,self.cell.size)785 cells = self.cell_local 723 786 assert len(rarr) == len(cells) 724 787 for cell,val in zip(cells,rarr): 725 788 try: 726 789 nest.SetStatus([cell],{parametername: val}) 727 except nest.SLIError: 790 #except nest.SLIError: 791 except Exception: # unfortunately, SLIError seems to have disappeared. 728 792 raise common.InvalidParameterValueError 729 793 … … 833 897 _print(filename, gather=gather, compatible_output=compatible_output, 834 898 population=self, variable="spikes") 835 899 900 def getSpikes(self): 901 """ 902 Returns a numpy array of the spikes of the population 903 904 Useful for small populations, for example for single neuron Monte-Carlo. 905 906 NOTE: getSpikes or printSpikes should be called only once per run, 907 because they mangle simulator recorder files. 908 """ 909 return _get(population=self, variable="spikes") 910 836 911 def meanSpikeCount(self, gather=True): 837 912 """ … … 1006 1081 def _fixedNumberPre(self,parameters): 1007 1082 """Each presynaptic cell makes a fixed number of connections.""" 1008 allow_self_connections = True 1009 if type(parameters) == types.IntType: 1010 n = parameters 1011 assert n > 0 1012 fixed = True 1013 elif type(parameters) == types.DictType: 1014 if parameters.has_key('n'): # all cells have same number of connections 1015 n = int(parameters['n']) 1016 assert n > 0 1017 fixed = True 1018 elif parameters.has_key('rand_distr'): # number of connections per cell follows a distribution 1019 rand_distr = parameters['rand_distr'] 1020 assert isinstance(rand_distr,RandomDistribution) 1021 fixed = False 1022 if parameters.has_key('allow_self_connections'): 1023 allow_self_connections = parameters['allow_self_connections'] 1024 elif isinstance(parameters, RandomDistribution): 1025 rand_distr = parameters 1026 fixed = False 1027 else: 1028 raise Exception("Invalid argument type: should be an integer, dictionary or RandomDistribution object.") 1029 1030 postsynaptic_neurons = numpy.reshape(self.post.cell,(self.post.cell.size,)) 1031 presynaptic_neurons = numpy.reshape(self.pre.cell,(self.pre.cell.size,)) 1032 if self.rng: 1033 rng = self.rng 1034 else: 1035 rng = numpy.random 1036 for pre in presynaptic_neurons: 1037 pre_addr = nest.getAddress(pre) 1038 # Reserve space for connections 1039 if not fixed: 1040 n = rand_distr.next() 1041 nest.resCons(pre_addr,n) 1042 # pick n neurons at random 1043 for post in rng.permutation(postsynaptic_neurons)[0:n]: 1044 if allow_self_connections or (pre != post): 1045 self._sources.append(pre) 1046 self._targets.append(post) 1047 self._targetPorts.append(nest.connect(pre_addr,nest.getAddress(post))) 1083 n = parameters['n'] 1084 if parameters.has_key('allow_self_connections'): 1085 allow_self_connections = parameters['allow_self_connections'] 1086 c = FixedNumberPreConnector(n, allow_self_connections) 1087 return c.connect(self) 1048 1088 1049 1089 def _fixedNumberPost(self,parameters): 1050 1090 """Each postsynaptic cell receives a fixed number of connections.""" 1051 allow_self_connections = True 1052 if type(parameters) == types.IntType: 1053 n = parameters 1054 assert n > 0 1055 fixed = True 1056 elif type(parameters) == types.DictType: 1057 if parameters.has_key('n'): # all cells have same number of connections 1058 n = int(parameters['n']) 1059 assert n > 0 1060 fixed = True 1061 elif parameters.has_key('rand_distr'): # number of connections per cell follows a distribution 1062 rand_distr = parameters['rand_distr'] 1063 assert isinstance(rand_distr,RandomDistribution) 1064 fixed = False 1065 if parameters.has_key('allow_self_connections'): 1066 allow_self_connections = parameters['allow_self_connections'] 1067 elif isinstance(parameters, RandomDistribution): 1068 rand_distr = parameters 1069 fixed = False 1070 else: 1071 raise Exception("Invalid argument type: should be an integer, dictionary or RandomDistribution object.") 1072 1073 postsynaptic_neurons = numpy.reshape(self.post.cell,(self.post.cell.size,)) 1074 presynaptic_neurons = numpy.reshape(self.pre.cell,(self.pre.cell.size,)) 1075 if self.rng: 1076 rng = self.rng 1077 else: 1078 rng = numpy.random 1079 for post in postsynaptic_neurons: 1080 post_addr = nest.getAddress(post) 1081 # Reserve space for connections 1082 if not fixed: 1083 n = rand_distr.next() 1084 nest.resCons(post_addr,n) 1085 # pick n neurons at random 1086 for pre in rng.permutation(presynaptic_neurons)[0:n]: 1087 if allow_self_connections or (pre != post): 1088 self._sources.append(pre) 1089 self._targets.append(post) 1090 self._targetPorts.append(nest.connect(nest.getAddress(pre),post_addr)) 1091 n = parameters['n'] 1092 if parameters.has_key('allow_self_connections'): 1093 allow_self_connections = parameters['allow_self_connections'] 1094 c = FixedNumberPostConnector(n, allow_self_connections) 1095 return c.connect(self) 1091 1096 1092 1097 def _fromFile(self,parameters): … … 1261 1266 f = open(filename,'w',10000) 1262 1267 # Note unit change from pA to nA or nS to uS, depending on synapse type 1263 weights = [0.001*nest.GetWeight(src,port) for (src,port) in self.connections()] 1264 delays = [nest.GetDelay(src,port) for (src,port) in self.connections()] 1268 def getWD(wd, src, port): 1269 conn_dict = nest.GetConnection([src],'static_synapse',port) 1270 if isinstance(conn_dict, dict): 1271 return conn_dict[wd] 1272 else: 1273 raise Exception("Either the source id (%s) or the port number (%s) or both is invalid." % (src, port)) 1274 #weights = [0.001*nest.GetConnection([src],'static_synapse',port)['weight'] for (src,port) in self.connections()] 1275 #delays = [nest.GetConnection([src],'static_synapse',port)['delay'] for (src,port) in self.connections()] 1276 weights = [0.001*getWD('weight',src,port) for (src,port) in self.connections()] 1277 delays = [getWD('delay',src,port) for (src,port) in self.connections()] 1265 1278 fmt = "%s%s\t%s%s\t%s\t%s\n" % (self.pre.label,"%s",self.post.label,"%s","%g","%g") 1266 1279 for i in xrange(len(self)): branches/multifile/src/nest2/cells.py
r185 r186 27 27 self.parameters = self.translate1(self.parameters) 28 28 29 29 30 class IF_curr_exp(common.IF_curr_exp): 30 31 """Leaky integrate and fire model with fixed threshold and … … 49 50 self.parameters = self.translate1(self.parameters) 50 51 52 51 53 class IF_cond_alpha(common.IF_cond_alpha): 52 54 """Leaky integrate and fire model with fixed threshold and alpha-function- … … 97 99 # values for not-specified parameters. 98 100 self.parameters = self.translate1(self.parameters) 101 102 103 class IF_cond_exp_sfa_rr(common.IF_cond_exp_sfa_rr): 104 """Linear leaky integrate and fire model with fixed threshold, 105 decaying-exponential post-synaptic conductance, conductance based spike-frequency adaptation, 106 and a conductance-based relative refractory mechanism. 107 108 See: Muller et al (2007) Spike-frequency adapting neural ensembles: Beyond mean-adaptation 109 and renewal theories. Neural Computation 19: 2958-3010. 110 """ 111 translations = common.build_translations( 112 ('v_rest', 'E_L') , 113 ('v_reset', 'V_reset'), 114 ('cm', 'C_m', 1000.0), # C_m is in pF, cm in nF 115 ('tau_m', 'g_L', "cm/tau_m*1000.0", "C_m/g_L"), 116 ('tau_refrac', 't_ref', "max(dt, tau_refrac)", "t_ref"), 117 ('tau_syn_E', 'tau_syn_ex'), 118 ('tau_syn_I', 'tau_syn_in'), 119 ('v_thresh', 'V_th'), 120 ('i_offset', 'I_e', 1000.0), # I_e is in pA, i_offset in nA 121 ('e_rev_E', 'E_ex'), 122 ('e_rev_I', 'E_in'), 123 ('v_init', 'V_m'), 124 ('tau_sfa', 'tau_sfa'), 125 ('e_rev_sfa', 'E_sfa'), 126 ('q_sfa', 'q_sfa'), 127 ('tau_rr', 'tau_rr'), 128 ('e_rev_rr', 'E_rr'), 129 ('q_rr', 'q_rr') 130 ) 131 nest_name = "iaf_cond_exp_sfa_rr" 132 def __init__(self,parameters): 133 common.IF_cond_exp_sfa_rr.__init__(self,parameters) # checks supplied parameters and adds default 134 # values for not-specified parameters. 135 self.parameters = self.translate1(self.parameters) 136 137 138 class IF_facets_hardware1(common.IF_facets_hardware1): 139 """Leaky integrate and fire model with conductance-based synapses and fixed 140 threshold as it is resembled by the FACETS Hardware Stage 1. For further 141 details regarding the hardware model see the FACETS-internal Wiki: 142 https://facets.kip.uni-heidelberg.de/private/wiki/index.php/WP7_NNM 143 """ 144 # in 'iaf_cond_exp_sfa_rr', the dimension of C_m is pF, 145 # while in the pyNN context, cm is given in nF 146 translations = { 147 'v_reset' : ('V_reset', "parameters['v_reset']"), 148 'v_rest' : ('E_L', "parameters['v_rest']"), 149 'v_thresh' : ('V_th', "parameters['v_thresh']"), 150 'e_rev_E' : ('E_ex', "parameters['e_rev_E']"), 151 'e_rev_I' : ('E_in', "parameters['e_rev_I']"), 152 'cm' : ('C_m', "parameters['cm']*1000.0"), 153 'tau_refrac': ('t_ref', "max(dt,parameters['tau_refrac'])"), 154 'tau_syn_E' : ('tau_syn_ex', "parameters['tau_syn_E']"), 155 'tau_syn_I' : ('tau_syn_in', "parameters['tau_syn_I']"), 156 'g_leak' : ('g_L', "parameters['g_leak']") 157 } 158 nest_name = "iaf_cond_exp_sfa_rr" 159 160 def __init__(self, parameters): 161 common.IF_facets_hardware1.__init__(self,parameters) 162 self.parameters = self.translate(self.parameters) 163 self.parameters['q_rr'] = 0.0 164 self.parameters['q_sfa'] = 0.0 99 165 100 166 … … 124 190 # values for not-specified parameters. 125 191 self.parameters = self.translate(self.parameters) 192 126 193 127 194 class AdaptiveExponentialIF_alpha(common.AdaptiveExponentialIF_alpha): … … 154 221 self.parameters = self.translate1(self.parameters) 155 222 223 156 224 class SpikeSourcePoisson(common.SpikeSourcePoisson): 157 225 """Spike source, generating spikes according to a Poisson process.""" … … 168 236 self.parameters = self.translate(self.parameters) 169 237 self.parameters['origin'] = 1.0 170 238 239 240 class SpikeSourceInhGamma(common.SpikeSourceInhGamma): 241 """Spike source, generating realizations of an inhomogeneous gamma process, employing 242 the thinning method. 243 244 See: Muller et al (2007) Spike-frequency adapting neural ensembles: Beyond mean-adaptation 245 and renewal theories. Neural Computation 19: 2958-3010. 246 """ 247 248 translations = { 249 'a' : ('a' , "parameters['a']"), 250 'b' : ('b' , "parameters['b']"), 251 'tbins' : ('tbins' , "parameters['tbins']"), 252 'rmax' : ('rmax' , "parameters['rmax']"), 253 'start' : ('start' , "parameters['start']"), 254 'duration' : ('stop' , "parameters['duration']+parameters['start']") 255 } 256 nest_name = 'inh_gamma_generator' 257 258 def __init__(self,parameters): 259 common.SpikeSourceInhGamma.__init__(self,parameters) 260 self.parameters = self.translate(self.parameters) 261 self.parameters['origin'] = 1.0 262 263 171 264 class SpikeSourceArray(common.SpikeSourceArray): 172 265 """Spike source generating spikes at the times given in the spike_times array.""" branches/multifile/src/nest2/connectors.py
r185 r186 7 7 from pyNN.random import RandomDistribution, NativeRNG 8 8 from math import * 9 10 def get_target_ports(pre, target_list): 11 # The connection dict returned by NEST contains a list of target ids, 12 # so it is possible to obtain the target port by finding the index of 13 # the target in this list. For now, we stick with saving the target port 14 # in Python (faster, but more memory needed), but PyNEST should soon have 15 # a function to do the lookup, at which point we will switch to using that. 16 conn_dict = nest.GetConnections([pre], 'static_synapse')[0] 17 if conn_dict: 18 first_port = len(conn_dict['targets']) 19 else: 20 first_port = 0 21 return range(first_port, first_port+len(target_list)) 9 22 10 23 class AllToAllConnector(common.AllToAllConnector, WDManager): … … 33 46 projection._targets += target_list 34 47 projection._sources += [pre]*N 35 #conn_dict = nest.GetConnections([pre], 'static_synapse')[0] 36 projection._targetPorts += target_list 48 projection._targetPorts += get_target_ports(pre, target_list) 37 49 nest.DivergentConnectWD([pre], target_list, weights, delays) 38 50 return len(projection._targets) … … 47 59 projection._sources = projection.pre.cell.flatten() 48 60 projection._targets = projection.post.cell.flatten() 49 projection._targetPorts = projection.post.cell.flatten()50 61 N = len(projection._sources) 62 projection._targetPorts = range(N) 51 63 if isinstance(weight, RandomDistribution): 52 64 weights = list(weight.next(N)) … … 90 102 projection._targets += target_list 91 103 projection._sources += [pre]*N 92 projection._targetPorts += target_list104 projection._targetPorts += get_target_ports(pre, target_list) 93 105 nest.DivergentConnectWD([pre], target_list, weights, delays) 94 106 return len(projection._sources) … … 144 156 projection._targets += target_list 145 157 projection._sources += [pre]*N 146 projection._targetPorts += target_list158 projection._targetPorts += get_target_ports(pre, target_list) 147 159 nest.DivergentConnectWD([pre], target_list, weights, delays) 148 160 return len(projection._sources) … … 152 164 153 165 def connect(self, projection): 154 raise Exception("Not implemented yet !") 155 166 npost = projection.post.size 167 postsynaptic_neurons = projection.post.cell.flatten() 168 if projection.rng: 169 rng = projection.rng 170 else: 171 rng = numpy.random 172 for pre in projection.pre.cell.flat: 173 if hasattr(self, 'rand_distr'): 174 n = self.rand_distr.next() 175 else: 176 n = self.n 177 target_list = rng.permutation(postsynaptic_neurons)[0:n] 178 # if self connections are not allowed, check whether pre and post are the same 179 if not self.allow_self_connections and pre in target_list: 180 target_list.remove(pre) 181 182 N = len(target_list) 183 weights = 1000.0*self.getWeights(N) 184 if projection.synapse_type == 'inhibitory': 185 weights *= -1 186 delays = self.getDelays(N) 187 188 nest.DivergentConnectWD([pre], target_list.tolist(), weights.tolist(), delays.tolist()) 189 190 projection._sources += [pre]*N 191 conn_dict = nest.GetConnections([pre], 'static_synapse')[0] 192 if isinstance(conn_dict, dict): 193 all_targets = conn_dict['targets'] 194 total_targets = len(all_targets) 195 projection._targets += all_targets[-N:] 196 projection._targetPorts += range(total_targets-N,total_targets) 197 return len(projection._sources) 198 199 def _n_connections(population): 200 """ 201 Get a list of the total number of connections made by each neuron in a 202 population. 203 """ 204 n = numpy.zeros((len(population),),'int') 205 conn_dict_list = nest.GetConnections([id for id in population],'static_synapse') 206 for i, conn_dict in enumerate(conn_dict_list): 207 assert isinstance(conn_dict, dict) 208 n[i] = len(conn_dict['targets']) 209 return n 156 210 157 211 class FixedNumberPostConnector(common.FixedNumberPostConnector): 158 212 159 213 def connect(self, projection): 160 raise Exception("Not implemented yet !") 214 npre = projection.pre.size 215 presynaptic_neurons = projection.pre.cell.flatten() 216 if projection.rng: 217 rng = projection.rng 218 else: 219 rng = numpy.random 220 start_ports = _n_connections(projection.pre) 221 for post in projection.post.cell.flat: 222 if hasattr(self, 'rand_distr'): 223 n = self.rand_distr.next() 224 else: 225 n = self.n 226 source_list = rng.permutation(presynaptic_neurons)[0:n] 227 # if self connections are not allowed, check whether pre and post are the same 228 if not self.allow_self_connections and pre in source_list: 229 source_list.remove(pre) 230 231 N = len(source_list) 232 weights = 1000.0*self.getWeights(N) 233 if projection.synapse_type == 'inhibitory': 234 weights *= -1 235 delays = self.getDelays(N) 236 237 nest.ConvergentConnectWD(source_list.tolist(), [post], weights.tolist(), delays.tolist()) 238 239 end_ports = _n_connections(projection.pre) 240 for pre, start_port, end_port in zip(presynaptic_neurons, start_ports, end_ports): 241 projection._targetPorts += range(start_port, end_port) 242 projection._sources += [pre]*(end_port-start_port) 243 conn_dict = nest.GetConnections([pre], 'static_synapse')[0] 244 if isinstance(conn_dict, dict): 245 projection._targets += conn_dict['targets'][start_port:end_port] 246 print start_ports 247 print end_ports 248 return len(projection._sources) branches/multifile/test
- Property svn:ignore set to
recordTestSpikeFile1.txt
recordTestVmFile1.txt
- Property svn:ignore set to
branches/multifile/test/nest2tests.py
r162 r186 10 10 import numpy 11 11 import os 12 13 def get_weight(src, port): 14 conn_dict = nest.nest.GetConnection([src], 'static_synapse', port) 15 if isinstance(conn_dict, dict): 16 return conn_dict['weight'] 17 else: 18 raise Exception("Either the source id (%s) or the port number (%s) or both is invalid." % (src, port)) 19 20 def get_delay(src, port): 21 conn_dict = nest.nest.GetConnection([src], 'static_synapse', port) 22 if isinstance(conn_dict, dict): 23 return conn_dict['delay'] 24 else: 25 raise Exception("Either the source id (%s) or the port number (%s) or both is invalid." % (src, port)) 12 26 13 27 # ============================================================================== … … 399 413 nest.setup(max_delay=0.5) 400 414 nest.Population.nPop = 0 401 self.target33 = nest.Population((3,3),nest.IF_curr_alpha )402  
