Changeset 711

Show
Ignore:
Timestamp:
02/16/10 10:59:22 (2 years ago)
Author:
apdavison
Message:

Moved Error classes out of common into an errors module (see ticket:157)

Location:
trunk
Files:
1 added
15 modified

Legend:

Unmodified
Added
Removed
  • trunk/setup.py

    r708 r711  
    4141setup( 
    4242    name = "PyNN", 
    43     version = "0.6.0pre", 
     43    version = "0.7pre", 
    4444    package_dir={'pyNN': 'src'}, 
    4545    packages = ['pyNN','pyNN.nest', 'pyNN.pcsim', 'pyNN.neuron', 'pyNN.brian', 'pyNN.recording'], 
  • trunk/src/__init__.py

    r706 r711  
    6666""" 
    6767 
    68 __version__ = '0.6.0pre ( $Rev$)'.replace(' $','') 
    69 __all__ = ["common", "random", "nest", "neuron", "pcsim", "brian", "recording"] 
     68__version__ = '0.7pre ( $Rev$)'.replace(' $','') 
     69__all__ = ["common", "random", "nest", "neuron", "pcsim", "brian", "recording", "errors"] 
    7070 
  • trunk/src/brian/cells.py

    r698 r711  
    55""" 
    66 
    7 from pyNN import common, cells 
     7from pyNN import common, cells, errors 
    88#import brian_no_units_no_warnings 
    99from brian.library.synapses import * 
     
    199199                parameters['spike_times'] = numpy.array(parameters['spike_times'], float) 
    200200            except ValueError: 
    201                 raise common.InvalidParameterValueError("spike times must be floats") 
     201                raise errors.InvalidParameterValueError("spike times must be floats") 
    202202        return super(SpikeSourceArray, cls).translate(parameters) 
    203203 
  • trunk/src/brian/simulator.py

    r702 r711  
    3232from itertools import izip 
    3333import scipy.sparse 
    34 from pyNN import common, cells 
     34from pyNN import common, cells, errors 
    3535 
    3636mV = brian.mV 
     
    267267            eqs = brian.Equations(cellclass) 
    268268        except Exception, errmsg: 
    269             raise common.InvalidModelError(errmsg) 
     269            raise errors.InvalidModelError(errmsg) 
    270270        v_thresh   = cellparams['v_thresh'] 
    271271        v_reset    = cellparams['v_reset'] 
     
    477477        assert len(targets) > 0 
    478478        if not isinstance(source, common.IDMixin): 
    479             raise common.ConnectionError("source should be an ID object, actually %s" % type(source)) 
     479            raise errors.ConnectionError("source should be an ID object, actually %s" % type(source)) 
    480480        for target in targets: 
    481481            if not isinstance(target, common.IDMixin): 
    482                 raise common.ConnectionError("Invalid target ID: %s" % target) 
     482                raise errors.ConnectionError("Invalid target ID: %s" % target) 
    483483        assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) 
    484484        if common.is_conductance(targets[0]): 
     
    492492            source_group = source.parent_group 
    493493        except AttributeError, errmsg: 
    494             raise common.ConnectionError("%s. Maybe trying to connect from non-existing cell (ID=%s)." % (errmsg, source)) 
     494            raise errors.ConnectionError("%s. Maybe trying to connect from non-existing cell (ID=%s)." % (errmsg, source)) 
    495495        target_group = targets[0].parent_group # we assume here all the targets belong to the same NeuronGroup 
    496496        bc = self._get_brian_connection(source_group, 
  • trunk/src/common.py

    r702 r711  
    77consistent with good performance (optimisations may require overriding some of 
    88the default definitions given here). 
    9  
    10 Exceptions: 
    11     InvalidParameterValueError 
    12     NonExistentParameterError 
    13     InvalidDimensionsError 
    14     ConnectionError 
    15     InvalidModelError 
    16     RoundingWarning 
    17     NothingToWriteError 
    18     InvalidWeightError 
    19     NotLocalError 
    20     RecordingError     
    219 
    2210Utility functions and classes: 
     
    2715    check_delay() 
    2816    distance() 
    29     distances() 
    30     next_n() 
    31     ConstIter 
    3217     
    3318Accessing individual neurons: 
     
    6146    Population 
    6247    Projection 
    63     Connector 
    6448     
    6549  4. Specification of synaptic plasticity: 
     
    7862from math import * 
    7963import operator 
    80 from pyNN import random, utility, recording 
     64from pyNN import random, utility, recording, errors 
    8165from string import Template 
    8266 
     
    8973logger = logging.getLogger("PyNN") 
    9074 
    91 class InvalidParameterValueError(ValueError): 
    92     """Inappropriate parameter value""" 
    93     pass 
    94  
    95 class NonExistentParameterError(Exception): 
    96     """ 
    97     Model parameter does not exist. 
    98     """ 
    99      
    100     def __init__(self, parameter_name, model): 
    101         self.parameter_name = parameter_name 
    102         if isinstance(model, type): 
    103             if issubclass(model, StandardModelType): 
    104                 self.model_name = model.__name__ 
    105                 self.valid_parameter_names = model.default_parameters.keys() 
    106                 self.valid_parameter_names.sort() 
    107         elif isinstance(model, basestring): 
    108             self.model_name = model 
    109             self.valid_parameter_names = ['unknown'] 
    110         else: 
    111             raise Exception("When raising a NonExistentParameterError, model must be a class or a string, not a %s" % type(model)) 
    112  
    113     def __str__(self): 
    114         return "%s (valid parameters for %s are: %s)" % (self.parameter_name, 
    115                                                          self.model_name, 
    116                                                          ", ".join(self.valid_parameter_names)) 
    117  
    118 class InvalidDimensionsError(Exception): 
    119     """Argument has inappropriate shape/dimensions.""" 
    120     pass 
    121  
    122 class ConnectionError(Exception): 
    123     """Attempt to create an invalid connection or access a non-existent connection.""" 
    124     pass 
    125  
    126 class InvalidModelError(Exception): 
    127     """Attempt to use a non-existent model type.""" 
    128     pass 
    129  
    130 class NoModelAvailableError(Exception): 
    131     """The simulator does not implement the requested model.""" 
    132     pass 
    133  
    134 class RoundingWarning(Warning): 
    135     """The argument has been rounded to a lower level of precision by the simulator.""" 
    136     pass 
    137  
    138 class NothingToWriteError(Exception): 
    139     """There is no data available to write.""" 
    140     pass # subclass IOError? 
    141  
    142 class InvalidWeightError(Exception): # subclass ValueError? or InvalidParameterValueError? 
    143     """Invalid value for the synaptic weight.""" 
    144     pass 
    145  
    146 class NotLocalError(Exception): 
    147     """Attempt to access a cell or connection that does not exist on this node (but exists elsewhere).""" 
    148     pass 
    149  
    150 class RecordingError(Exception): # subclass AttributeError? 
    151     """Attempt to record a variable that does not exist for this cell type.""" 
    152      
    153     def __init__(self, variable, cell_type): 
    154         self.variable = variable 
    155         self.cell_type = cell_type 
    156          
    157     def __str__(self): 
    158         return "Cannot record %s from cell type %s" % (self.variable, self.cell_type.__class__.__name__) 
    15975 
    16076 
     
    194110        all_positive = (filtered_weight>=0).all() 
    195111        if not (all_negative or all_positive): 
    196             raise InvalidWeightError("Weights must be either all positive or all negative") 
     112            raise errors.InvalidWeightError("Weights must be either all positive or all negative") 
    197113    elif is_number(weight): 
    198114        all_positive = weight >= 0 
     
    202118    if is_conductance or synapse_type == 'excitatory': 
    203119        if not all_positive: 
    204             raise InvalidWeightError("Weights must be positive for conductance-based and/or excitatory synapses") 
     120            raise errors.InvalidWeightError("Weights must be positive for conductance-based and/or excitatory synapses") 
    205121    elif is_conductance==False and synapse_type == 'inhibitory': 
    206122        if not all_negative: 
    207             raise InvalidWeightError("Weights must be negative for current-based, inhibitory synapses") 
     123            raise errors.InvalidWeightError("Weights must be negative for current-based, inhibitory synapses") 
    208124    else: # is_conductance is None. This happens if the cell does not exist on the current node. 
    209125        logger.debug("Can't check weight, conductance status unknown.") 
     
    215131    # If the delay is too small , we have to throw an error 
    216132    if delay < get_min_delay() or delay > get_max_delay(): 
    217         raise ConnectionError("delay (%s) is out of range [%s,%s]" % (delay, get_min_delay(), get_max_delay())) 
     133        raise errors.ConnectionError("delay (%s) is out of range [%s,%s]" % (delay, get_min_delay(), get_max_delay())) 
    218134    return delay 
    219135 
     
    323239                val = self.get_parameters()[name] 
    324240            except KeyError: 
    325                 raise NonExistentParameterError(name, self.cellclass) 
     241                raise errors.NonExistentParameterError(name, self.cellclass.__name__, 
     242                                                self.cellclass.default_parameters.keys()) 
    326243        return val 
    327244     
     
    492409                            parameters[k] = float(supplied_parameters[k])  
    493410                        except (ValueError, TypeError): 
    494                             raise InvalidParameterValueError(err_msg) 
     411                            raise errors.InvalidParameterValueError(err_msg) 
    495412                    # list and something that can be transformed to a list 
    496413                    elif type(default_parameters[k]) == types.ListType: 
     
    498415                            parameters[k] = list(supplied_parameters[k]) 
    499416                        except TypeError: 
    500                             raise InvalidParameterValueError(err_msg) 
     417                            raise errors.InvalidParameterValueError(err_msg) 
    501418                    else: 
    502                         raise InvalidParameterValueError(err_msg) 
     419                        raise errors.InvalidParameterValueError(err_msg) 
    503420                else: 
    504                     raise NonExistentParameterError(k, cls) 
     421                    raise errors.NonExistentParameterError(k, cls) 
    505422        return parameters 
    506423     
     
    683600    for tgt in target: 
    684601        #if not isinstance(tgt, IDMixin): 
    685         #    raise ConnectionError("target is not a cell, actually %s" % type(tgt)) 
     602        #    raise errors.ConnectionError("target is not a cell, actually %s" % type(tgt)) 
    686603        sources = numpy.array(source, dtype=type(source)) 
    687604        if p < 1: 
     
    794711            id = self.all_cells[addr] 
    795712        else: 
    796             raise InvalidDimensionsError, "Population has %d dimensions. Address was %s" % (self.ndim, str(addr)) 
     713            raise errors.InvalidDimensionsError, "Population has %d dimensions. Address was %s" % (self.ndim, str(addr)) 
    797714        return id 
    798715     
     
    844761            coords = (idx,) 
    845762        else: 
    846             raise common.InvalidDimensionsError 
     763            raise errors.InvalidDimensionsError 
    847764        return coords 
    848765     
     
    933850                param_dict = {param: val} 
    934851            else: 
    935                 raise InvalidParameterValueError 
     852                raise errors.InvalidParameterValueError 
    936853        elif isinstance(param, dict): 
    937854            param_dict = param 
    938855        else: 
    939             raise InvalidParameterValueError 
     856            raise errors.InvalidParameterValueError 
    940857        logger.debug("%s.set(%s)", self.label, param_dict) 
    941858        for cell in self: 
     
    953870            local_values = value_array[self._mask_local] # not sure this works 
    954871        else: 
    955             raise InvalidDimensionsError, "Population: %s, value_array: %s" % (str(self.dim), 
     872            raise errors.InvalidDimensionsError, "Population: %s, value_array: %s" % (str(self.dim), 
    956873                                                                               str(value_array.shape)) 
    957874        assert local_values.shape[0] == self.local_cells.size, "%d != %d" % (local_values.size, self.local_cells.size) 
     
    1017934        """ 
    1018935        if not self.can_record(variable): 
    1019             raise RecordingError(variable, self.celltype) 
     936            raise errors.RecordingError(variable, self.celltype) 
    1020937        if isinstance(record_from, list): #record from the fixed list specified by user 
    1021938            pass 
  • trunk/src/connectors.py

    r703 r711  
    2020                  fabs, floor, fmod, hypot, ldexp, log, log10, modf, pi, power, \ 
    2121                  sin, sinh, sqrt, tan, tanh 
    22 from pyNN import random, common 
     22from pyNN import random, common, errors 
    2323 
    2424logger = logging.getLogger("PyNN") 
     
    447447                projection.connection_manager.connect(src, [tgt], float(w), float(d)) 
    448448        else: 
    449             raise common.InvalidDimensionsError("OneToOneConnector does not support presynaptic and postsynaptic Populations of different sizes.") 
     449            raise errors.InvalidDimensionsError("OneToOneConnector does not support presynaptic and postsynaptic Populations of different sizes.") 
    450450 
    451451 
  • trunk/src/nest/__init__.py

    r701 r711  
    77import nest 
    88from pyNN.nest import simulator 
    9 from pyNN import common, recording, __doc__ 
     9from pyNN import common, recording, errors, __doc__ 
    1010common.simulator = simulator 
    1111recording.simulator = simulator 
     
    217217                param_dict = {param: float(val)} 
    218218            else: 
    219                 raise common.InvalidParameterValueError 
     219                raise errors.InvalidParameterValueError 
    220220        elif isinstance(param,dict): 
    221221            param_dict = param 
    222222        else: 
    223             raise common.InvalidParameterValueError 
     223            raise errors.InvalidParameterValueError 
    224224         
    225225        # The default implementation in common is is not very efficient for 
     
    237237                    self.celltype.default_parameters[key] 
    238238                except Exception: 
    239                     raise common.NonExistentParameterError(key, self.celltype.__class__) 
     239                    raise errors.NonExistentParameterError(key, self.celltype.__class__) 
    240240                if type(value) != type(self.celltype.default_parameters[key]): 
    241241                    if isinstance(value, int) and isinstance(self.celltype.default_parameters[key], float): 
    242242                        value = float(value) 
    243243                    else: 
    244                         raise common.InvalidParameterValueError("The parameter %s should be a %s, you supplied a %s" % (key, 
     244                        raise errors.InvalidParameterValueError("The parameter %s should be a %s, you supplied a %s" % (key, 
    245245                                                                                                                        type(self.celltype.default_parameters[key]), 
    246246                                                                                                                        type(value))) 
     
    264264                    nest.SetStatus(self.local_cells, key, value) 
    265265                except Exception: 
    266                     raise common.InvalidParameterValueError 
     266                    raise errors.InvalidParameterValueError 
    267267 
    268268    #def rset(self, parametername, rand_distr): 
     
    282282    #                self.celltype.default_parameters[parametername] 
    283283    #            except Exception: 
    284     #                raise common.NonExistentParameterError(parametername, self.celltype.__class__) 
     284    #                raise errors.NonExistentParameterError(parametername, self.celltype.__class__) 
    285285    #            if parametername == 'v_init': 
    286286    #                for cell,val in zip(self.local_cells, rarr): 
  • trunk/src/nest/recording.py

    r695 r711  
    44import logging 
    55import nest 
    6 from pyNN import recording, common 
     6from pyNN import recording, common, errors 
    77from pyNN.nest import simulator 
    88 
     
    163163        else: 
    164164            if "filename" not in nest.GetStatus(self._device)[0]: # indicates that run() has not been called. 
    165                 raise common.NothingToWriteError("No data. Have you called run()?") 
     165                raise errors.NothingToWriteError("No data. Have you called run()?") 
    166166            if simulator.state.num_threads > 1: 
    167167                nest_files = [] 
     
    191191        """Return the recorded data as a Numpy array.""" 
    192192        if self._device is None: 
    193             raise common.NothingToWriteError("No cells recorded, so no data to return") 
     193            raise errors.NothingToWriteError("No cells recorded, so no data to return") 
    194194         
    195195        if self.in_memory(): 
     
    202202        """Write recorded data to file.""" 
    203203        if self._device is None: 
    204             raise common.NothingToWriteError("%s not recorded from any cells, so no data to write to file." % self.variable) 
     204            raise errors.NothingToWriteError("%s not recorded from any cells, so no data to write to file." % self.variable) 
    205205        recording.Recorder.write(self, file, gather, compatible_output) 
    206206 
  • trunk/src/nest/simulator.py

    r708 r711  
    2727 
    2828import nest 
    29 from pyNN import common, random 
     29from pyNN import common, random, errors 
    3030import logging 
    3131import numpy 
     
    120120            exc_type, exc_value, traceback = sys.exc_info() 
    121121            if exc_type == 'NESTError' and "Unsupported Numpy array type" in exc_value: 
    122                 raise common.InvalidParameterValueError() 
     122                raise errors.InvalidParameterValueError() 
    123123            else: 
    124124                raise 
     
    159159        cell_gids = nest.Create(nest_model, n) 
    160160    except nest.NESTError, errmsg: 
    161         raise common.InvalidModelError(errmsg) 
     161        raise errors.InvalidModelError(errmsg) 
    162162    if cell_parameters: 
    163163        try: 
     
    317317        assert len(targets) > 0 
    318318        if self.synapse_type not in ('excitatory', 'inhibitory', None): 
    319             raise common.ConnectionError("synapse_type must be 'excitatory', 'inhibitory', or None (equivalent to 'excitatory')") 
     319            raise errors.ConnectionError("synapse_type must be 'excitatory', 'inhibitory', or None (equivalent to 'excitatory')") 
    320320        weights = weights*1000.0 # weights should be in nA or uS, but iaf_neuron uses pA and iaf_cond_neuron uses nS. 
    321321                                 # Using convention in this way is not ideal. We should 
     
    335335            nest.DivergentConnect([source], targets, weights, delays, self.synapse_model)             
    336336        except nest.NESTError, e: 
    337             raise common.ConnectionError("%s. source=%s, targets=%s, weights=%s, delays=%s, synapse model='%s'" % ( 
     337            raise errors.ConnectionError("%s. source=%s, targets=%s, weights=%s, delays=%s, synapse model='%s'" % ( 
    338338                                         e, source, targets, weights, delays, self.synapse_model)) 
    339339        self._connections = None # reset the caching of the connection list, since this will have to be recalculated 
     
    358358        assert len(sources) > 0, sources 
    359359        if self.synapse_type not in ('excitatory', 'inhibitory', None): 
    360             raise common.ConnectionError("synapse_type must be 'excitatory', 'inhibitory', or None (equivalent to 'excitatory')") 
     360            raise errors.ConnectionError("synapse_type must be 'excitatory', 'inhibitory', or None (equivalent to 'excitatory')") 
    361361        weights = weights*1000.0 # weights should be in nA or uS, but iaf_neuron uses pA and iaf_cond_neuron uses nS. 
    362362                                 # Using convention in this way is not ideal. We should 
     
    376376            nest.ConvergentConnect(sources, [target], weights, delays, self.synapse_model)             
    377377        except nest.NESTError, e: 
    378             raise common.ConnectionError("%s. sources=%s, target=%s, weights=%s, delays=%s, synapse model='%s'" % ( 
     378            raise errors.ConnectionError("%s. sources=%s, target=%s, weights=%s, delays=%s, synapse model='%s'" % ( 
    379379                                         e, sources, target, weights, delays, self.synapse_model)) 
    380380        self._connections = None # reset the caching of the connection list, since this will have to be recalculated 
  • trunk/src/neuron/cells.py

    r704 r711  
    66""" 
    77 
    8 from pyNN import common, cells 
     8from pyNN import common, cells, errors 
    99from neuron import h, nrn, hclass 
    1010from math import pi 
     
    402402            self._spike_times = h.Vector(spike_times) 
    403403        except RuntimeError: 
    404             raise common.InvalidParameterValueError("spike_times must be an array of floats") 
     404            raise errors.InvalidParameterValueError("spike_times must be an array of floats") 
    405405        self.play(self._spike_times) 
    406406             
  • trunk/src/neuron/simulator.py

    r702 r711  
    2929 
    3030from pyNN import __path__ as pyNN_path 
    31 from pyNN import common, random 
     31from pyNN import common, random, errors 
    3232import platform 
    3333import logging 
     
    282282            cell_model = getattr(h, cellclass) 
    283283        except AttributeError: 
    284             raise common.InvalidModelError("There is no hoc template called %s" % cellclass) 
     284            raise errors.InvalidModelError("There is no hoc template called %s" % cellclass) 
    285285        cell_parameters = cellparams or {} 
    286286    elif isinstance(cellclass, type) and issubclass(cellclass, common.StandardCellType): 
     
    463463        if not isinstance(source, int) or source > state.gid_counter or source < 0: 
    464464            errmsg = "Invalid source ID: %s (gid_counter=%d)" % (source, state.gid_counter) 
    465             raise common.ConnectionError(errmsg) 
     465            raise errors.ConnectionError(errmsg) 
    466466        if not common.is_listlike(targets): 
    467467            targets = [targets] 
     
    473473        for target in targets: 
    474474            if not isinstance(target, common.IDMixin): 
    475                 raise common.ConnectionError("Invalid target ID: %s" % target) 
     475                raise errors.ConnectionError("Invalid target ID: %s" % target) 
    476476               
    477477        assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) 
  • trunk/src/pcsim/__init__.py

    r701 r711  
    1515 
    1616import pyNN.random 
    17 from pyNN import common, recording, __doc__ 
     17from pyNN import common, recording, errors, __doc__ 
    1818from pyNN.pcsim import simulator 
    1919common.simulator = simulator 
     
    223223#    if delay  is None:  delay = simulator.state.min_delay 
    224224#    if delay < get_min_delay(): 
    225 #        raise common.ConnectionError("Delay (%g ms) must be >= the minimum delay (%g ms)" % (delay, get_min_delay())) 
     225#        raise errors.ConnectionError("Delay (%g ms) must be >= the minimum delay (%g ms)" % (delay, get_min_delay())) 
    226226#    # Convert units 
    227227#    delay = delay / 1000 # Delays in pcsim are specified in seconds 
     
    236236#            weight = 1e-9 * weight # Convert from nA to A 
    237237#    except exceptions.Exception, e: # non-existent connection 
    238 #        raise common.ConnectionError(e) 
     238#        raise errors.ConnectionError(e) 
    239239#    # Create synapse factory 
    240240#    syn_factory = 0 
     
    274274#            return connections.idVector() 
    275275#    except exceptions.TypeError, e: 
    276 #        raise common.ConnectionError(e) 
     276#        raise errors.ConnectionError(e) 
    277277#    except exceptions.Exception, e: 
    278 #        raise common.ConnectionError(e) 
     278#        raise errors.ConnectionError(e) 
    279279connect = common.connect 
    280280set = common.set     
     
    333333        if isinstance(cellclass, str): 
    334334            if not cellclass in dir(pypcsim): 
    335                 raise common.InvalidModelError('Trying to create non-existent cellclass ' + cellclass ) 
     335                raise errors.InvalidModelError('Trying to create non-existent cellclass ' + cellclass ) 
    336336            cellclass = getattr(pypcsim, cellclass) 
    337337            self.celltype = cellclass 
     
    379379    ##        addr = (addr,) 
    380380    ##    if len(addr) != self.actual_ndim: 
    381     ##       raise common.InvalidDimensionsError, "Population has %d dimensions. Address was %s" % (self.actual_ndim, str(addr)) 
     381    ##       raise errors.InvalidDimensionsError, "Population has %d dimensions. Address was %s" % (self.actual_ndim, str(addr)) 
    382382    ##    orig_addr = addr; 
    383383    ##    while len(addr) < 3: 
     
    427427    ##        coords = (id,) 
    428428    ##    else: 
    429     ##        raise common.InvalidDimensionsError 
     429    ##        raise errors.InvalidDimensionsError 
    430430    ##    if self.actual_ndim == 1: 
    431431    ##        if coords[0] > self.dim[0]: 
     
    470470    ##            setattr(cell, parametername, val) 
    471471    ##    else: 
    472     ##        raise common.InvalidDimensionsError 
     472    ##        raise errors.InvalidDimensionsError 
    473473         
    474474    ##def rset(self, parametername, rand_distr): 
     
    655655                 
    656656            if len(possible_models) == 0: 
    657                 raise common.NoModelAvailableError("The synapse model requested is not available.") 
     657                raise errors.NoModelAvailableError("The synapse model requested is not available.") 
    658658            synapse_type = getattr(pypcsim, list(possible_models)[0]) 
    659659            try: 
  • trunk/src/pcsim/cells.py

    r700 r711  
    55""" 
    66 
    7 from pyNN import common, cells 
     7from pyNN import common, cells, errors 
    88import pypcsim 
    99import numpy 
     
    151151        spike_times = numpy.array(spike_times, float) 
    152152    except ValueError, e: 
    153         raise common.InvalidParameterValueError("Spike times must be floats. %s") 
     153        raise errors.InvalidParameterValueError("Spike times must be floats. %s") 
    154154     
    155155    bins = (spike_times/time_step).astype('int') 
  • trunk/src/pcsim/simulator.py

    r702 r711  
    3030import types 
    3131import numpy 
    32 from pyNN import common 
     32from pyNN import common, errors 
    3333 
    3434recorder_list = [] 
     
    156156            cellfactory = cellclass(**cellparams) 
    157157        else: 
    158             raise common.InvalidModelError("Trying to create non-existent cellclass %s" % cellclass.__name__) 
     158            raise errors.InvalidModelError("Trying to create non-existent cellclass %s" % cellclass.__name__) 
    159159    else: 
    160         raise common.InvalidModelError("Trying to create non-existent cellclass %s" % cellclass) 
     160        raise errors.InvalidModelError("Trying to create non-existent cellclass %s" % cellclass) 
    161161 
    162162    all_ids = numpy.array([i for i in net.add(cellfactory, n)], ID) 
     
    275275        if not isinstance(source, (int, long)) or source < 0: 
    276276            errmsg = "Invalid source ID: %s" % source 
    277             raise common.ConnectionError(errmsg) 
     277            raise errors.ConnectionError(errmsg) 
    278278        if not common.is_listlike(targets): 
    279279            targets = [targets] 
     
    285285        for target in targets: 
    286286            if not isinstance(target, common.IDMixin): 
    287                 raise common.ConnectionError("Invalid target ID: %s" % target) 
     287                raise errors.ConnectionError("Invalid target ID: %s" % target) 
    288288        assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) 
    289289        if common.is_conductance(targets[0]): 
     
    300300            syn_factory = synapse_type 
    301301        else: 
    302             raise common.ConnectionError("synapse_type must be a string or a PCSIM synapse factory. Actual type is %s" % type(synapse_type)) 
     302            raise errors.ConnectionError("synapse_type must be a string or a PCSIM synapse factory. Actual type is %s" % type(synapse_type)) 
    303303        for target, weight, delay in zip(targets, weights, delays): 
    304304            syn_factory.W = weight*weight_scale_factor 
     
    307307                c = net.connect(source, target, syn_factory) 
    308308            except RuntimeError, e: 
    309                 raise common.ConnectionError(e) 
     309                raise errors.ConnectionError(e) 
    310310            if target.local: 
    311311                self.connections.append(Connection(source, target, net.object(c), 1.0/weight_scale_factor)) 
  • trunk/test/unittests/generictests.py

    r702 r711  
    99import os 
    1010import cPickle as pickle 
    11 from pyNN import common, random, utility, recording 
     11from pyNN import common, random, utility, recording, errors 
    1212import glob 
    1313 
     
    6666        """create(): Trying to create a cell type which is not a standard cell or 
    6767        valid native cell should raise an Exception.""" 
    68         self.assertRaises(common.InvalidModelError, sim.create, 'qwerty', n=10) 
     68        self.assertRaises(errors.InvalidModelError, sim.create, 'qwerty', n=10) 
    6969     
    7070    def testCreateWithInvalidParameter(self): 
    7171        """create(): Creating a cell with an invalid parameter should raise an Exception.""" 
    72         self.assertRaises(common.NonExistentParameterError, sim.create, sim.IF_curr_alpha, {'tau_foo':3.141592654})   
     72        self.assertRaises(errors.NonExistentParameterError, sim.create, sim.IF_curr_alpha, {'tau_foo':3.141592654})   
    7373 
    7474# ============================================================================== 
     
    136136        """connect(): Connecting from non-existent cell should raise a ConnectionError.""" 
    137137        if self.postcells[0].local: 
    138             self.assertRaises(common.ConnectionError, sim.connect, 12345, self.postcells[0]) 
     138            self.assertRaises(errors.ConnectionError, sim.connect, 12345, self.postcells[0]) 
    139139         
    140140    def testConnectNonExistentPostCell(self): 
    141141        """connect(): Connecting to a non-existent cell should raise a ConnectionError.""" 
    142         self.assertRaises(common.ConnectionError, sim.connect, self.precells[0], 'cell45678') 
     142        self.assertRaises(errors.ConnectionError, sim.connect, self.precells[0], 'cell45678') 
    143143     
    144144    def testInvalidSourceId(self): 
    145145        """connect(): sources must be integers.""" 
    146146        self.precells.append('74367598') 
    147         self.assertRaises(common.ConnectionError, sim.connect, self.precells, self.postcells) 
     147        self.assertRaises(errors.ConnectionError, sim.connect, self.precells, self.postcells) 
    148148     
    149149    def testInvalidTargetId(self): 
    150150        """connect(): targets must be integers.""" 
    151151        self.postcells.append('99.9') 
    152         self.assertRaises(common.ConnectionError, sim.connect, self.precells, self.postcells) 
     152        self.assertRaises(errors.ConnectionError, sim.connect, self.precells, self.postcells) 
    153153     
    154154    def testConnectTooSmallDelay(self): 
    155         self.assertRaises(common.ConnectionError, sim.connect, self.precells[0], self.postcells[0], delay=1e-12) 
     155        self.assertRaises(errors.ConnectionError, sim.connect, self.precells[0], self.postcells[0], delay=1e-12) 
    156156 
    157157# ============================================================================== 
     
    295295            try: 
    296296                self.assertAlmostEqual(cell.tau_m, 35.7, 5) 
    297             except common.NotLocalError: # if cell is not on this node 
     297            except errors.NotLocalError: # if cell is not on this node 
    298298                pass 
    299299        if self.single_cell.local: 
     
    306306                self.assertAlmostEqual(cell.tau_syn_E, 5.432, 6) 
    307307                self.assertAlmostEqual(cell.tau_m, 35.7, 5) 
    308             except common.NotLocalError: # if cell is not on this node 
     308            except errors.NotLocalError: # if cell is not on this node 
    309309                pass 
    310310             
     
    312312        # note that although syn_shape is added to the NEURON parameter dict when creating 
    313313        # an IF_curr_exp, it is not a valid parameter to be changed later. 
    314         self.assertRaises(common.NonExistentParameterError, sim.set, self.cells, 'syn_shape', 'alpha') 
     314        self.assertRaises(errors.NonExistentParameterError, sim.set, self.cells, 'syn_shape', 'alpha') 
    315315     
    316316# ============================================================================== 
     
    340340     
    341341    def testInvalidCellType(self): 
    342         self.assertRaises(common.InvalidModelError, sim.Population, (3,3), 'qwerty', {}) 
     342        self.assertRaises(errors.InvalidModelError, sim.Population, (3,3), 'qwerty', {}) 
    343343         
    344344# ============================================================================== 
     
    377377         
    378378    def testInvalidIndexDimension(self): 
    379         self.assertRaises(common.InvalidDimensionsError, self.net1.__getitem__, (10,2)) 
     379        self.assertRaises(errors.InvalidDimensionsError, self.net1.__getitem__, (10,2)) 
    380380         
    381381# ============================================================================== 
     
    475475                 
    476476    def test_set_invalid_type(self): 
    477         self.assertRaises(common.InvalidParameterValueError, self.p1.set, 'foo', {}) 
    478         self.assertRaises(common.InvalidParameterValueError, self.p1.set, [1,2,3]) 
     477        self.assertRaises(errors.InvalidParameterValueError, self.p1.set, 'foo', {}) 
     478        self.assertRaises(errors.InvalidParameterValueError, self.p1.set, [1,2,3]) 
    479479                 
    480480    def testSetInvalidFromDict(self): 
    481         self.assertRaises(common.InvalidParameterValueError, self.p1.set, {'v_thresh':'hello','tau_m':56.78}) 
     481        self.assertRaises(errors.InvalidParameterValueError, self.p1.set, {'v_thresh':'hello','tau_m':56.78}) 
    482482             
    483483    def testSetNonexistentFromPair(self): 
    484484        """Population.set(): Trying to set a nonexistent parameter should raise an exception.""" 
    485         self.assertRaises(common.NonExistentParameterError, self.p1.set, 'tau_foo', 10.0) 
     485        self.assertRaises(errors.NonExistentParameterError, self.p1.set, 'tau_foo', 10.0) 
    486486     
    487487    def testSetNonexistentFromDict(self): 
    488488        """Population.set(): When some of the parameters in a dict are inexistent, an exception should be raised. 
    489489           There is no guarantee that the existing parameters will be set.""" 
    490         self.assertRaises(common.NonExistentParameterError, self.p1.set, {'tau_foo': 10.0, 'tau_m': 21.0}) 
     490        self.assertRaises(errors.NonExistentParameterError, self.p1.set, {'tau_foo': 10.0, 'tau_m': 21.0}) 
    491491             
    492492    def testRandomInit(self): 
     
    516516        """Population.tset(): If the size of the valueArray does not match that of the Population, should raise an InvalidDimensionsError.""" 
    517517        array_in = numpy.array([[0.1,0.2,0.3],[0.4,0.5,0.6]]) 
    518         self.assertRaises(common.InvalidDimensionsError, self.p1.tset, 'i_offset', array_in) 
     518        self.assertRaises(errors.InvalidDimensionsError, self.p1.tset, 'i_offset', array_in) 
    519519     
    520520    def testTSetInvalidValues(self): 
    521521        """Population.tset(): If some of the values in the valueArray are invalid, should raise an exception.""" 
    522522        array_in = numpy.array([['potatoes','carrots'],['oranges','bananas']]) 
    523         self.assertRaises(common.InvalidParameterValueError, self.p2.tset, 'spike_times', array_in) 
     523        self.assertRaises(errors.InvalidParameterValueError, self.p2.tset, 'spike_times', array_in) 
    524524         
    525525    def testRSetNumpy(self): 
     
    648648    def testSynapticConductanceRecording(self): 
    649649        # current-based synapses 
    650         self.assertRaises(common.RecordingError, self.pop2.record_gsyn) 
     650        self.assertRaises(errors.RecordingError, self.pop2.record_gsyn) 
    651651        # conductance-based synapses 
    652652        cells_to_record = [self.pop3[1,0], self.pop3[2,2]] 
     
    674674 
    675675    def testRecordVmFromSpikeSource(self): 
    676         self.assertRaises(common.RecordingError, self.pop1.record_v) 
     676        self.assertRaises(errors.RecordingError, self.pop1.record_v) 
    677677         
    678678     
     
    896896            result = 2.345*numpy.ones(len(prj.connections)) 
    897897            assert_arrays_almost_equal(numpy.array(weights), result, 1e-7, msg=prj.label) 
    898         self.assertRaises(common.InvalidWeightError, prj2.setWeights, 2.345) # current-based inhibitory needs negative weights 
     898        self.assertRaises(errors.InvalidWeightError, prj2.setWeights, 2.345) # current-based inhibitory needs negative weights 
    899899             
    900900    def testSetNegativeWeights(self): 
     
    910910        assert_arrays_almost_equal(numpy.array(weights), result, 1e-7) 
    911911        for prj in prj1, prj3, prj4: 
    912             self.assertRaises(common.InvalidWeightError, prj.setWeights, -2.345)  
     912            self.assertRaises(errors.InvalidWeightError, prj.setWeights, -2.345)  
    913913     
    914914    def test_set_weights_with_array(self):