Changeset 711 for trunk/src/common.py

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)

Files:
1 modified

Legend:

Unmodified
Added
Removed
  • 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