Changeset 186

Show
Ignore:
Timestamp:
01/28/08 17:45:43 (10 months ago)
Author:
apdavison
Message:

Merged changes from trunk r183 for common.py, nest2/__init.py__, nest2/cells.py and nest2/connectors.py and test directory. Merging largely done by hand since svn merge can't handle all the moving around/splitting of files (or if it can, I don't know how to do it). Merging of nest1, neuron and pcsim remains to be done.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/multifile

    • Property svn:ignore set to
      build
      .project
      .pydevproject
  • branches/multifile/src/common.py

    r181 r186  
    1111import numpy 
    1212from math import * 
    13  
     13from pyNN import random 
    1414 
    1515class InvalidParameterValueError(Exception): pass 
     
    1919 
    2020dt = 0.1 
     21_min_delay = 0.1 
    2122 
    2223# ============================================================================== 
     
    189190     
    190191    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        """ 
    192202        default_parameters = self.__class__.default_parameters 
    193203        if with_defaults: 
     
    237247        return translated_parameters 
    238248 
     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 
    239256    def __init__(self,parameters): 
    240257        self.parameters = self.checkParameters(parameters, with_defaults=True) 
     
    312329        'i_offset'   : 0.0,     # Offset current in nA 
    313330        'v_init'     : -65.0,   # Membrane potential in mV at t = 0 
     331    } 
     332 
     333class 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     
     365class 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         
    314383    } 
    315384 
     
    370439    }   
    371440 
     441class 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 
    372460class SpikeSourceArray(StandardCellType): 
    373461    """Spike source generating spikes at the times given in the spike_times array.""" 
     
    628716        return _abstractMethod(self) 
    629717     
     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 
    630731    def print_v(self,filename,gather=True, compatible_output=True): 
    631732        """ 
     
    9011002 
    9021003class 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 
    9071011     
    9081012    def connect(self,projection): 
    9091013        """Connect all neurons in ``projection``""" 
    9101014        _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     
    9121048class AllToAllConnector(Connector): 
    9131049    """ 
     
    9161052    """ 
    9171053     
    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) 
    9191056        assert isinstance(allow_self_connections, bool) 
    9201057        self.allow_self_connections = allow_self_connections 
    921         self.weights = weights 
    922         self.delays = delays 
    923  
    924  
     1058         
    9251059class FixedNumberPostConnector(Connector): 
    9261060    """ 
    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) 
    9311067        assert isinstance(allow_self_connections, bool) 
    9321068        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") 
    9371078 
    9381079class FixedNumberPreConnector(Connector): 
     
    9411082    cells in the presynaptic population, randomly choosen. 
    9421083    """ 
    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) 
    9441086        assert isinstance(allow_self_connections, bool) 
    9451087        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") 
    9491097 
    9501098class OneToOneConnector(Connector): 
     
    9591107    """ 
    9601108     
    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) 
    9651111     
    9661112class FixedProbabilityConnector(Connector): 
     
    9691115    """ 
    9701116     
    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) 
    9721119        assert isinstance(allow_self_connections, bool) 
    9731120        self.allow_self_connections = allow_self_connections 
    974         self.weights = weights 
    975         self.delays = delays 
    9761121        self.p_connect = float(p_connect) 
    9771122        assert 0 <= self.p_connect 
     
    9861131    axes='xyz' is the same as axes=None. 
    9871132    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 applied 
     1133    degrees and µm. In this case, `scale_factor` can be specified, which is applied 
    9891134    to the positions in the post-synaptic population. An offset can also be included. 
    9901135    """ 
     
    9931138            'xy': [0,1], 'yz': [1,2], 'xz': [0,2], 'xyz': None, None: None} 
    9941139     
    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) 
    9961144        assert isinstance(allow_self_connections, bool) 
    9971145        assert isinstance(d_expression, str) 
     
    10041152        self.d_expression = d_expression 
    10051153        self.allow_self_connections = allow_self_connections 
    1006         self.weights = weights 
    1007         self.delays = delays 
    10081154        self.mask = DistanceDependentProbabilityConnector.AXES[axes] 
    10091155        self.periodic_boundaries = periodic_boundaries 
     
    10121158        self.scale_factor = scale_factor 
    10131159        self.offset = offset 
     1160         
     1161 
    10141162         
    10151163# ============================================================================== 
  • branches/multifile/src/nest2/__init__.py

    r185 r186  
    44$Id$ 
    55""" 
    6 __version__ = "$Revision:5 $" 
     6__version__ = "$Rev$" 
    77 
    88import nest 
     
    351351                        nest.ConnectWD([src],[tgt],[weight],[delay]) 
    352352                        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. 
    354355        raise common.ConnectionError 
    355356    return connect_id 
     
    447448        os.remove(nest_filename) 
    448449    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") 
    450453        if nest.Rank() == 0: # only on the master node (?) 
    451454            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    
    454461    if compatible_output: 
    455462        if gather == False or nest.Rank() == 0: # if we gather, only do this on the master node 
     
    465472            ## Writing header info (e.g., dimensions of the population) 
    466473            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]) 
    468477                padding = population.cell.flatten()[0] 
    469478            else: 
     
    504513        recorder_dict.pop(user_filename)     
    505514 
     515def _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 
    506562def _readArray(filename, sepchar=None, skipchar='#'): 
    507563    logging.debug(filename) 
     
    625681    def ids(self): 
    626682        return self.__iter__() 
    627      
     683 
    628684    def locate(self, id): 
    629685        """Given an element id in a Population, return the coordinates. 
     
    656712        return coords 
    657713     
     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     
    658720    def set(self,param,val=None): 
    659721        """ 
     
    676738        if isinstance(self.celltype, common.StandardCellType): 
    677739            paramDict = self.celltype.translate1(paramDict) 
    678         nest.SetStatus(numpy.reshape(self.cell,(self.size,)), [paramDict]) 
    679          
     740        nest.SetStatus(self.cell_local, [paramDict]) 
    680741 
    681742    def tset(self,parametername,valueArray): 
     
    702763                        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. 
    703764                    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. 
    706769                    raise common.InvalidParameterValueError, "Error from SLI" 
    707770        else: 
     
    720783        else: 
    721784            rarr = rand_distr.next(n=self.size) 
    722             cells = numpy.reshape(self.cell,self.cell.size) 
     785            cells = self.cell_local 
    723786            assert len(rarr) == len(cells) 
    724787            for cell,val in zip(cells,rarr): 
    725788                try: 
    726789                    nest.SetStatus([cell],{parametername: val}) 
    727                 except nest.SLIError: 
     790                #except nest.SLIError: 
     791                except Exception: # unfortunately, SLIError seems to have disappeared. 
    728792                    raise common.InvalidParameterValueError 
    729793             
     
    833897        _print(filename, gather=gather, compatible_output=compatible_output, 
    834898               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     
    836911    def meanSpikeCount(self, gather=True): 
    837912        """ 
     
    10061081    def _fixedNumberPre(self,parameters): 
    10071082        """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) 
    10481088     
    10491089    def _fixedNumberPost(self,parameters): 
    10501090        """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) 
    10911096     
    10921097    def _fromFile(self,parameters): 
     
    12611266        f = open(filename,'w',10000) 
    12621267        # 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()] 
    12651278        fmt = "%s%s\t%s%s\t%s\t%s\n" % (self.pre.label,"%s",self.post.label,"%s","%g","%g") 
    12661279        for i in xrange(len(self)): 
  • branches/multifile/src/nest2/cells.py

    r185 r186  
    2727        self.parameters = self.translate1(self.parameters) 
    2828 
     29 
    2930class IF_curr_exp(common.IF_curr_exp): 
    3031    """Leaky integrate and fire model with fixed threshold and 
     
    4950        self.parameters = self.translate1(self.parameters) 
    5051 
     52 
    5153class IF_cond_alpha(common.IF_cond_alpha): 
    5254    """Leaky integrate and fire model with fixed threshold and alpha-function- 
     
    9799                                                       # values for not-specified parameters. 
    98100        self.parameters = self.translate1(self.parameters) 
     101         
     102 
     103class 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 
     138class 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 
    99165         
    100166 
     
    124190                                                     # values for not-specified parameters. 
    125191        self.parameters = self.translate(self.parameters) 
     192         
    126193         
    127194class AdaptiveExponentialIF_alpha(common.AdaptiveExponentialIF_alpha): 
     
    154221        self.parameters = self.translate1(self.parameters) 
    155222         
     223         
    156224class SpikeSourcePoisson(common.SpikeSourcePoisson): 
    157225    """Spike source, generating spikes according to a Poisson process.""" 
     
    168236        self.parameters = self.translate(self.parameters) 
    169237        self.parameters['origin'] = 1.0 
    170      
     238 
     239 
     240class 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 
    171264class SpikeSourceArray(common.SpikeSourceArray): 
    172265    """Spike source generating spikes at the times given in the spike_times array.""" 
  • branches/multifile/src/nest2/connectors.py

    r185 r186  
    77from pyNN.random import RandomDistribution, NativeRNG 
    88from math import * 
     9 
     10def 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)) 
    922 
    1023class AllToAllConnector(common.AllToAllConnector, WDManager):     
     
    3346            projection._targets += target_list 
    3447            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) 
    3749            nest.DivergentConnectWD([pre], target_list, weights, delays) 
    3850        return len(projection._targets) 
     
    4759            projection._sources = projection.pre.cell.flatten() 
    4860            projection._targets = projection.post.cell.flatten() 
    49             projection._targetPorts = projection.post.cell.flatten() 
    5061            N = len(projection._sources) 
     62            projection._targetPorts = range(N) 
    5163            if isinstance(weight, RandomDistribution): 
    5264                weights = list(weight.next(N)) 
     
    90102            projection._targets += target_list 
    91103            projection._sources += [pre]*N 
    92             projection._targetPorts += target_list 
     104            projection._targetPorts += get_target_ports(pre, target_list) 
    93105            nest.DivergentConnectWD([pre], target_list, weights, delays) 
    94106        return len(projection._sources) 
     
    144156            projection._targets += target_list 
    145157            projection._sources += [pre]*N  
    146             projection._targetPorts += target_list 
     158            projection._targetPorts += get_target_ports(pre, target_list) 
    147159            nest.DivergentConnectWD([pre], target_list, weights, delays) 
    148160        return len(projection._sources) 
     
    152164     
    153165    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 
     199def _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 
    156210 
    157211class FixedNumberPostConnector(common.FixedNumberPostConnector): 
    158212     
    159213    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
  • branches/multifile/test/nest2tests.py

    r162 r186  
    1010import numpy 
    1111import os 
     12 
     13def 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 
     20def 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)) 
    1226 
    1327# ============================================================================== 
     
    399413        nest.setup(max_delay=0.5) 
    400414        nest.Population.nPop = 0 
    401         self.target33 = nest.Population((3,3),nest.IF_curr_alpha
    402