Changeset 711
- Timestamp:
- 02/16/10 10:59:22 (2 years ago)
- Location:
- trunk
- Files:
-
- 1 added
- 15 modified
-
setup.py (modified) (1 diff)
-
src/__init__.py (modified) (1 diff)
-
src/brian/cells.py (modified) (2 diffs)
-
src/brian/simulator.py (modified) (4 diffs)
-
src/common.py (modified) (17 diffs)
-
src/connectors.py (modified) (2 diffs)
-
src/errors.py (added)
-
src/nest/__init__.py (modified) (5 diffs)
-
src/nest/recording.py (modified) (4 diffs)
-
src/nest/simulator.py (modified) (7 diffs)
-
src/neuron/cells.py (modified) (2 diffs)
-
src/neuron/simulator.py (modified) (4 diffs)
-
src/pcsim/__init__.py (modified) (9 diffs)
-
src/pcsim/cells.py (modified) (2 diffs)
-
src/pcsim/simulator.py (modified) (6 diffs)
-
test/unittests/generictests.py (modified) (14 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/setup.py
r708 r711 41 41 setup( 42 42 name = "PyNN", 43 version = "0. 6.0pre",43 version = "0.7pre", 44 44 package_dir={'pyNN': 'src'}, 45 45 packages = ['pyNN','pyNN.nest', 'pyNN.pcsim', 'pyNN.neuron', 'pyNN.brian', 'pyNN.recording'], -
trunk/src/__init__.py
r706 r711 66 66 """ 67 67 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"] 70 70 -
trunk/src/brian/cells.py
r698 r711 5 5 """ 6 6 7 from pyNN import common, cells 7 from pyNN import common, cells, errors 8 8 #import brian_no_units_no_warnings 9 9 from brian.library.synapses import * … … 199 199 parameters['spike_times'] = numpy.array(parameters['spike_times'], float) 200 200 except ValueError: 201 raise common.InvalidParameterValueError("spike times must be floats")201 raise errors.InvalidParameterValueError("spike times must be floats") 202 202 return super(SpikeSourceArray, cls).translate(parameters) 203 203 -
trunk/src/brian/simulator.py
r702 r711 32 32 from itertools import izip 33 33 import scipy.sparse 34 from pyNN import common, cells 34 from pyNN import common, cells, errors 35 35 36 36 mV = brian.mV … … 267 267 eqs = brian.Equations(cellclass) 268 268 except Exception, errmsg: 269 raise common.InvalidModelError(errmsg)269 raise errors.InvalidModelError(errmsg) 270 270 v_thresh = cellparams['v_thresh'] 271 271 v_reset = cellparams['v_reset'] … … 477 477 assert len(targets) > 0 478 478 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)) 480 480 for target in targets: 481 481 if not isinstance(target, common.IDMixin): 482 raise common.ConnectionError("Invalid target ID: %s" % target)482 raise errors.ConnectionError("Invalid target ID: %s" % target) 483 483 assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) 484 484 if common.is_conductance(targets[0]): … … 492 492 source_group = source.parent_group 493 493 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)) 495 495 target_group = targets[0].parent_group # we assume here all the targets belong to the same NeuronGroup 496 496 bc = self._get_brian_connection(source_group, -
trunk/src/common.py
r702 r711 7 7 consistent with good performance (optimisations may require overriding some of 8 8 the default definitions given here). 9 10 Exceptions:11 InvalidParameterValueError12 NonExistentParameterError13 InvalidDimensionsError14 ConnectionError15 InvalidModelError16 RoundingWarning17 NothingToWriteError18 InvalidWeightError19 NotLocalError20 RecordingError21 9 22 10 Utility functions and classes: … … 27 15 check_delay() 28 16 distance() 29 distances()30 next_n()31 ConstIter32 17 33 18 Accessing individual neurons: … … 61 46 Population 62 47 Projection 63 Connector64 48 65 49 4. Specification of synaptic plasticity: … … 78 62 from math import * 79 63 import operator 80 from pyNN import random, utility, recording 64 from pyNN import random, utility, recording, errors 81 65 from string import Template 82 66 … … 89 73 logger = logging.getLogger("PyNN") 90 74 91 class InvalidParameterValueError(ValueError):92 """Inappropriate parameter value"""93 pass94 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_name102 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 = model109 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 pass121 122 class ConnectionError(Exception):123 """Attempt to create an invalid connection or access a non-existent connection."""124 pass125 126 class InvalidModelError(Exception):127 """Attempt to use a non-existent model type."""128 pass129 130 class NoModelAvailableError(Exception):131 """The simulator does not implement the requested model."""132 pass133 134 class RoundingWarning(Warning):135 """The argument has been rounded to a lower level of precision by the simulator."""136 pass137 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 pass145 146 class NotLocalError(Exception):147 """Attempt to access a cell or connection that does not exist on this node (but exists elsewhere)."""148 pass149 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 = variable155 self.cell_type = cell_type156 157 def __str__(self):158 return "Cannot record %s from cell type %s" % (self.variable, self.cell_type.__class__.__name__)159 75 160 76 … … 194 110 all_positive = (filtered_weight>=0).all() 195 111 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") 197 113 elif is_number(weight): 198 114 all_positive = weight >= 0 … … 202 118 if is_conductance or synapse_type == 'excitatory': 203 119 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") 205 121 elif is_conductance==False and synapse_type == 'inhibitory': 206 122 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") 208 124 else: # is_conductance is None. This happens if the cell does not exist on the current node. 209 125 logger.debug("Can't check weight, conductance status unknown.") … … 215 131 # If the delay is too small , we have to throw an error 216 132 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())) 218 134 return delay 219 135 … … 323 239 val = self.get_parameters()[name] 324 240 except KeyError: 325 raise NonExistentParameterError(name, self.cellclass) 241 raise errors.NonExistentParameterError(name, self.cellclass.__name__, 242 self.cellclass.default_parameters.keys()) 326 243 return val 327 244 … … 492 409 parameters[k] = float(supplied_parameters[k]) 493 410 except (ValueError, TypeError): 494 raise InvalidParameterValueError(err_msg)411 raise errors.InvalidParameterValueError(err_msg) 495 412 # list and something that can be transformed to a list 496 413 elif type(default_parameters[k]) == types.ListType: … … 498 415 parameters[k] = list(supplied_parameters[k]) 499 416 except TypeError: 500 raise InvalidParameterValueError(err_msg)417 raise errors.InvalidParameterValueError(err_msg) 501 418 else: 502 raise InvalidParameterValueError(err_msg)419 raise errors.InvalidParameterValueError(err_msg) 503 420 else: 504 raise NonExistentParameterError(k, cls)421 raise errors.NonExistentParameterError(k, cls) 505 422 return parameters 506 423 … … 683 600 for tgt in target: 684 601 #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)) 686 603 sources = numpy.array(source, dtype=type(source)) 687 604 if p < 1: … … 794 711 id = self.all_cells[addr] 795 712 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)) 797 714 return id 798 715 … … 844 761 coords = (idx,) 845 762 else: 846 raise common.InvalidDimensionsError763 raise errors.InvalidDimensionsError 847 764 return coords 848 765 … … 933 850 param_dict = {param: val} 934 851 else: 935 raise InvalidParameterValueError852 raise errors.InvalidParameterValueError 936 853 elif isinstance(param, dict): 937 854 param_dict = param 938 855 else: 939 raise InvalidParameterValueError856 raise errors.InvalidParameterValueError 940 857 logger.debug("%s.set(%s)", self.label, param_dict) 941 858 for cell in self: … … 953 870 local_values = value_array[self._mask_local] # not sure this works 954 871 else: 955 raise InvalidDimensionsError, "Population: %s, value_array: %s" % (str(self.dim),872 raise errors.InvalidDimensionsError, "Population: %s, value_array: %s" % (str(self.dim), 956 873 str(value_array.shape)) 957 874 assert local_values.shape[0] == self.local_cells.size, "%d != %d" % (local_values.size, self.local_cells.size) … … 1017 934 """ 1018 935 if not self.can_record(variable): 1019 raise RecordingError(variable, self.celltype)936 raise errors.RecordingError(variable, self.celltype) 1020 937 if isinstance(record_from, list): #record from the fixed list specified by user 1021 938 pass -
trunk/src/connectors.py
r703 r711 20 20 fabs, floor, fmod, hypot, ldexp, log, log10, modf, pi, power, \ 21 21 sin, sinh, sqrt, tan, tanh 22 from pyNN import random, common 22 from pyNN import random, common, errors 23 23 24 24 logger = logging.getLogger("PyNN") … … 447 447 projection.connection_manager.connect(src, [tgt], float(w), float(d)) 448 448 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.") 450 450 451 451 -
trunk/src/nest/__init__.py
r701 r711 7 7 import nest 8 8 from pyNN.nest import simulator 9 from pyNN import common, recording, __doc__9 from pyNN import common, recording, errors, __doc__ 10 10 common.simulator = simulator 11 11 recording.simulator = simulator … … 217 217 param_dict = {param: float(val)} 218 218 else: 219 raise common.InvalidParameterValueError219 raise errors.InvalidParameterValueError 220 220 elif isinstance(param,dict): 221 221 param_dict = param 222 222 else: 223 raise common.InvalidParameterValueError223 raise errors.InvalidParameterValueError 224 224 225 225 # The default implementation in common is is not very efficient for … … 237 237 self.celltype.default_parameters[key] 238 238 except Exception: 239 raise common.NonExistentParameterError(key, self.celltype.__class__)239 raise errors.NonExistentParameterError(key, self.celltype.__class__) 240 240 if type(value) != type(self.celltype.default_parameters[key]): 241 241 if isinstance(value, int) and isinstance(self.celltype.default_parameters[key], float): 242 242 value = float(value) 243 243 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, 245 245 type(self.celltype.default_parameters[key]), 246 246 type(value))) … … 264 264 nest.SetStatus(self.local_cells, key, value) 265 265 except Exception: 266 raise common.InvalidParameterValueError266 raise errors.InvalidParameterValueError 267 267 268 268 #def rset(self, parametername, rand_distr): … … 282 282 # self.celltype.default_parameters[parametername] 283 283 # except Exception: 284 # raise common.NonExistentParameterError(parametername, self.celltype.__class__)284 # raise errors.NonExistentParameterError(parametername, self.celltype.__class__) 285 285 # if parametername == 'v_init': 286 286 # for cell,val in zip(self.local_cells, rarr): -
trunk/src/nest/recording.py
r695 r711 4 4 import logging 5 5 import nest 6 from pyNN import recording, common 6 from pyNN import recording, common, errors 7 7 from pyNN.nest import simulator 8 8 … … 163 163 else: 164 164 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()?") 166 166 if simulator.state.num_threads > 1: 167 167 nest_files = [] … … 191 191 """Return the recorded data as a Numpy array.""" 192 192 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") 194 194 195 195 if self.in_memory(): … … 202 202 """Write recorded data to file.""" 203 203 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) 205 205 recording.Recorder.write(self, file, gather, compatible_output) 206 206 -
trunk/src/nest/simulator.py
r708 r711 27 27 28 28 import nest 29 from pyNN import common, random 29 from pyNN import common, random, errors 30 30 import logging 31 31 import numpy … … 120 120 exc_type, exc_value, traceback = sys.exc_info() 121 121 if exc_type == 'NESTError' and "Unsupported Numpy array type" in exc_value: 122 raise common.InvalidParameterValueError()122 raise errors.InvalidParameterValueError() 123 123 else: 124 124 raise … … 159 159 cell_gids = nest.Create(nest_model, n) 160 160 except nest.NESTError, errmsg: 161 raise common.InvalidModelError(errmsg)161 raise errors.InvalidModelError(errmsg) 162 162 if cell_parameters: 163 163 try: … … 317 317 assert len(targets) > 0 318 318 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')") 320 320 weights = weights*1000.0 # weights should be in nA or uS, but iaf_neuron uses pA and iaf_cond_neuron uses nS. 321 321 # Using convention in this way is not ideal. We should … … 335 335 nest.DivergentConnect([source], targets, weights, delays, self.synapse_model) 336 336 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'" % ( 338 338 e, source, targets, weights, delays, self.synapse_model)) 339 339 self._connections = None # reset the caching of the connection list, since this will have to be recalculated … … 358 358 assert len(sources) > 0, sources 359 359 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')") 361 361 weights = weights*1000.0 # weights should be in nA or uS, but iaf_neuron uses pA and iaf_cond_neuron uses nS. 362 362 # Using convention in this way is not ideal. We should … … 376 376 nest.ConvergentConnect(sources, [target], weights, delays, self.synapse_model) 377 377 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'" % ( 379 379 e, sources, target, weights, delays, self.synapse_model)) 380 380 self._connections = None # reset the caching of the connection list, since this will have to be recalculated -
trunk/src/neuron/cells.py
r704 r711 6 6 """ 7 7 8 from pyNN import common, cells 8 from pyNN import common, cells, errors 9 9 from neuron import h, nrn, hclass 10 10 from math import pi … … 402 402 self._spike_times = h.Vector(spike_times) 403 403 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") 405 405 self.play(self._spike_times) 406 406 -
trunk/src/neuron/simulator.py
r702 r711 29 29 30 30 from pyNN import __path__ as pyNN_path 31 from pyNN import common, random 31 from pyNN import common, random, errors 32 32 import platform 33 33 import logging … … 282 282 cell_model = getattr(h, cellclass) 283 283 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) 285 285 cell_parameters = cellparams or {} 286 286 elif isinstance(cellclass, type) and issubclass(cellclass, common.StandardCellType): … … 463 463 if not isinstance(source, int) or source > state.gid_counter or source < 0: 464 464 errmsg = "Invalid source ID: %s (gid_counter=%d)" % (source, state.gid_counter) 465 raise common.ConnectionError(errmsg)465 raise errors.ConnectionError(errmsg) 466 466 if not common.is_listlike(targets): 467 467 targets = [targets] … … 473 473 for target in targets: 474 474 if not isinstance(target, common.IDMixin): 475 raise common.ConnectionError("Invalid target ID: %s" % target)475 raise errors.ConnectionError("Invalid target ID: %s" % target) 476 476 477 477 assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) -
trunk/src/pcsim/__init__.py
r701 r711 15 15 16 16 import pyNN.random 17 from pyNN import common, recording, __doc__17 from pyNN import common, recording, errors, __doc__ 18 18 from pyNN.pcsim import simulator 19 19 common.simulator = simulator … … 223 223 # if delay is None: delay = simulator.state.min_delay 224 224 # 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())) 226 226 # # Convert units 227 227 # delay = delay / 1000 # Delays in pcsim are specified in seconds … … 236 236 # weight = 1e-9 * weight # Convert from nA to A 237 237 # except exceptions.Exception, e: # non-existent connection 238 # raise common.ConnectionError(e)238 # raise errors.ConnectionError(e) 239 239 # # Create synapse factory 240 240 # syn_factory = 0 … … 274 274 # return connections.idVector() 275 275 # except exceptions.TypeError, e: 276 # raise common.ConnectionError(e)276 # raise errors.ConnectionError(e) 277 277 # except exceptions.Exception, e: 278 # raise common.ConnectionError(e)278 # raise errors.ConnectionError(e) 279 279 connect = common.connect 280 280 set = common.set … … 333 333 if isinstance(cellclass, str): 334 334 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 ) 336 336 cellclass = getattr(pypcsim, cellclass) 337 337 self.celltype = cellclass … … 379 379 ## addr = (addr,) 380 380 ## 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)) 382 382 ## orig_addr = addr; 383 383 ## while len(addr) < 3: … … 427 427 ## coords = (id,) 428 428 ## else: 429 ## raise common.InvalidDimensionsError429 ## raise errors.InvalidDimensionsError 430 430 ## if self.actual_ndim == 1: 431 431 ## if coords[0] > self.dim[0]: … … 470 470 ## setattr(cell, parametername, val) 471 471 ## else: 472 ## raise common.InvalidDimensionsError472 ## raise errors.InvalidDimensionsError 473 473 474 474 ##def rset(self, parametername, rand_distr): … … 655 655 656 656 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.") 658 658 synapse_type = getattr(pypcsim, list(possible_models)[0]) 659 659 try: -
trunk/src/pcsim/cells.py
r700 r711 5 5 """ 6 6 7 from pyNN import common, cells 7 from pyNN import common, cells, errors 8 8 import pypcsim 9 9 import numpy … … 151 151 spike_times = numpy.array(spike_times, float) 152 152 except ValueError, e: 153 raise common.InvalidParameterValueError("Spike times must be floats. %s")153 raise errors.InvalidParameterValueError("Spike times must be floats. %s") 154 154 155 155 bins = (spike_times/time_step).astype('int') -
trunk/src/pcsim/simulator.py
r702 r711 30 30 import types 31 31 import numpy 32 from pyNN import common 32 from pyNN import common, errors 33 33 34 34 recorder_list = [] … … 156 156 cellfactory = cellclass(**cellparams) 157 157 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__) 159 159 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) 161 161 162 162 all_ids = numpy.array([i for i in net.add(cellfactory, n)], ID) … … 275 275 if not isinstance(source, (int, long)) or source < 0: 276 276 errmsg = "Invalid source ID: %s" % source 277 raise common.ConnectionError(errmsg)277 raise errors.ConnectionError(errmsg) 278 278 if not common.is_listlike(targets): 279 279 targets = [targets] … … 285 285 for target in targets: 286 286 if not isinstance(target, common.IDMixin): 287 raise common.ConnectionError("Invalid target ID: %s" % target)287 raise errors.ConnectionError("Invalid target ID: %s" % target) 288 288 assert len(targets) == len(weights) == len(delays), "%s %s %s" % (len(targets),len(weights),len(delays)) 289 289 if common.is_conductance(targets[0]): … … 300 300 syn_factory = synapse_type 301 301 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)) 303 303 for target, weight, delay in zip(targets, weights, delays): 304 304 syn_factory.W = weight*weight_scale_factor … … 307 307 c = net.connect(source, target, syn_factory) 308 308 except RuntimeError, e: 309 raise common.ConnectionError(e)309 raise errors.ConnectionError(e) 310 310 if target.local: 311 311 self.connections.append(Connection(source, target, net.object(c), 1.0/weight_scale_factor)) -
trunk/test/unittests/generictests.py
r702 r711 9 9 import os 10 10 import cPickle as pickle 11 from pyNN import common, random, utility, recording 11 from pyNN import common, random, utility, recording, errors 12 12 import glob 13 13 … … 66 66 """create(): Trying to create a cell type which is not a standard cell or 67 67 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) 69 69 70 70 def testCreateWithInvalidParameter(self): 71 71 """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}) 73 73 74 74 # ============================================================================== … … 136 136 """connect(): Connecting from non-existent cell should raise a ConnectionError.""" 137 137 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]) 139 139 140 140 def testConnectNonExistentPostCell(self): 141 141 """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') 143 143 144 144 def testInvalidSourceId(self): 145 145 """connect(): sources must be integers.""" 146 146 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) 148 148 149 149 def testInvalidTargetId(self): 150 150 """connect(): targets must be integers.""" 151 151 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) 153 153 154 154 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) 156 156 157 157 # ============================================================================== … … 295 295 try: 296 296 self.assertAlmostEqual(cell.tau_m, 35.7, 5) 297 except common.NotLocalError: # if cell is not on this node297 except errors.NotLocalError: # if cell is not on this node 298 298 pass 299 299 if self.single_cell.local: … … 306 306 self.assertAlmostEqual(cell.tau_syn_E, 5.432, 6) 307 307 self.assertAlmostEqual(cell.tau_m, 35.7, 5) 308 except common.NotLocalError: # if cell is not on this node308 except errors.NotLocalError: # if cell is not on this node 309 309 pass 310 310 … … 312 312 # note that although syn_shape is added to the NEURON parameter dict when creating 313 313 # 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') 315 315 316 316 # ============================================================================== … … 340 340 341 341 def testInvalidCellType(self): 342 self.assertRaises( common.InvalidModelError, sim.Population, (3,3), 'qwerty', {})342 self.assertRaises(errors.InvalidModelError, sim.Population, (3,3), 'qwerty', {}) 343 343 344 344 # ============================================================================== … … 377 377 378 378 def testInvalidIndexDimension(self): 379 self.assertRaises( common.InvalidDimensionsError, self.net1.__getitem__, (10,2))379 self.assertRaises(errors.InvalidDimensionsError, self.net1.__getitem__, (10,2)) 380 380 381 381 # ============================================================================== … … 475 475 476 476 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]) 479 479 480 480 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}) 482 482 483 483 def testSetNonexistentFromPair(self): 484 484 """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) 486 486 487 487 def testSetNonexistentFromDict(self): 488 488 """Population.set(): When some of the parameters in a dict are inexistent, an exception should be raised. 489 489 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}) 491 491 492 492 def testRandomInit(self): … … 516 516 """Population.tset(): If the size of the valueArray does not match that of the Population, should raise an InvalidDimensionsError.""" 517 517 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) 519 519 520 520 def testTSetInvalidValues(self): 521 521 """Population.tset(): If some of the values in the valueArray are invalid, should raise an exception.""" 522 522 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) 524 524 525 525 def testRSetNumpy(self): … … 648 648 def testSynapticConductanceRecording(self): 649 649 # current-based synapses 650 self.assertRaises( common.RecordingError, self.pop2.record_gsyn)650 self.assertRaises(errors.RecordingError, self.pop2.record_gsyn) 651 651 # conductance-based synapses 652 652 cells_to_record = [self.pop3[1,0], self.pop3[2,2]] … … 674 674 675 675 def testRecordVmFromSpikeSource(self): 676 self.assertRaises( common.RecordingError, self.pop1.record_v)676 self.assertRaises(errors.RecordingError, self.pop1.record_v) 677 677 678 678 … … 896 896 result = 2.345*numpy.ones(len(prj.connections)) 897 897 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 weights898 self.assertRaises(errors.InvalidWeightError, prj2.setWeights, 2.345) # current-based inhibitory needs negative weights 899 899 900 900 def testSetNegativeWeights(self): … … 910 910 assert_arrays_almost_equal(numpy.array(weights), result, 1e-7) 911 911 for prj in prj1, prj3, prj4: 912 self.assertRaises( common.InvalidWeightError, prj.setWeights, -2.345)912 self.assertRaises(errors.InvalidWeightError, prj.setWeights, -2.345) 913 913 914 914 def test_set_weights_with_array(self):
