def make_step(self, signals, dt, rng): src = signals[self.src] dst = signals[self.dst] src_slice = self.src_slice if self.src_slice is not None else Ellipsis dst_slice = self.dst_slice if self.dst_slice is not None else Ellipsis inc = self.inc dst_slice = (np.asarray(dst_slice) if is_array_like(dst_slice) else dst_slice) # There are repeated indices in dst_slice, special case repeats = (is_array_like(dst_slice) and dst_slice.dtype != np.bool and len(np.unique(dst_slice)) < len(dst_slice)) if inc and repeats: def step_copy(): np.add.at(dst, dst_slice, src[src_slice]) elif inc: def step_copy(): dst[dst_slice] += src[src_slice] elif repeats: raise BuildError("%s: Cannot have repeated indices in " "``dst_slice`` when copy is not an increment" % self) else: def step_copy(): dst[dst_slice] = src[src_slice] return step_copy
def build_node(model, node): # input signal if not is_array_like(node.output) and node.size_in > 0: sig_in = Signal(np.zeros(node.size_in), name="%s.in" % node) model.add_op(Reset(sig_in)) else: sig_in = None # Provide output if node.output is None: sig_out = sig_in elif isinstance(node.output, Process): sig_out = Signal(np.zeros(node.size_out), name="%s.out" % node) model.build(node.output, sig_in, sig_out) elif callable(node.output): sig_out = (Signal(np.zeros(node.size_out), name="%s.out" % node) if node.size_out > 0 else None) model.add_op( SimPyFunc(output=sig_out, fn=node.output, t=model.time, x=sig_in)) elif is_array_like(node.output): sig_out = Signal(node.output, name="%s.out" % node) else: raise BuildError("Invalid node output type %r" % node.output.__class__.__name__) model.sig[node]['in'] = sig_in model.sig[node]['out'] = sig_out model.params[node] = None
def build_node(model, node): # input signal if not is_array_like(node.output) and node.size_in > 0: sig_in = Signal(np.zeros(node.size_in), name="%s.in" % node) model.add_op(Reset(sig_in)) else: sig_in = None # Provide output if node.output is None: sig_out = sig_in elif isinstance(node.output, Process): sig_out = Signal(np.zeros(node.size_out), name="%s.out" % node) model.build(node.output, sig_in, sig_out) elif callable(node.output): sig_out = (Signal(np.zeros(node.size_out), name="%s.out" % node) if node.size_out > 0 else None) model.add_op(SimPyFunc( output=sig_out, fn=node.output, t=model.time, x=sig_in)) elif is_array_like(node.output): sig_out = Signal(node.output, name="%s.out" % node) else: raise BuildError( "Invalid node output type %r" % node.output.__class__.__name__) model.sig[node]['in'] = sig_in model.sig[node]['out'] = sig_out model.params[node] = None
def equal(self, instance_a, instance_b): a = self.__get__(instance_a, None) b = self.__get__(instance_b, None) if self.equatable: if is_array_like(a) or is_array_like(b): return np.array_equal(a, b) else: return a == b else: return a is b
def coerce(self, conn, function): function = super(ConnectionFunctionParam, self).coerce(conn, function) if function is None: function_info = FunctionInfo(function=None, size=None) elif isinstance(function, FunctionInfo): function_info = function elif is_array_like(function): array = np.array(function, copy=False, dtype=np.float64) self.check_array(conn, array) function_info = FunctionInfo(function=array, size=array.shape[1]) elif callable(function): function_info = FunctionInfo(function=function, size=self.determine_size( conn, function)) # TODO: necessary? super(ConnectionFunctionParam, self).coerce(conn, function_info) else: raise ValidationError("Invalid connection function type %r " "(must be callable or array-like)" % type(function).__name__, attr=self.name, obj=conn) self.check_function_can_be_applied(conn, function_info) return function_info
def __init__(self, shape, init=1.0): super(Dense, self).__init__() self.shape = shape if is_array_like(init): init = np.asarray(init, dtype=np.float64) # check that the shape of init is compatible with the given shape # for this transform expected_shape = None if shape[0] != shape[1]: # init must be 2D if transform is not square expected_shape = shape elif init.ndim == 1: expected_shape = (shape[0], ) elif init.ndim >= 2: expected_shape = shape if expected_shape is not None and init.shape != expected_shape: raise ValidationError( "Shape of initial value %s does not match expected " "shape %s" % (init.shape, expected_shape), attr="init") self.init = init
def __set__(self, node, output): super(OutputParam, self).validate(node, output) size_in_set = node.size_in is not None node.size_in = node.size_in if size_in_set else 0 # --- Validate and set the new size_out if output is None: if node.size_out is not None: warnings.warn("'Node.size_out' is being overwritten with " "'Node.size_in' since 'Node.output=None'") node.size_out = node.size_in elif isinstance(output, Process): if not size_in_set: node.size_in = output.default_size_in if node.size_out is None: node.size_out = output.default_size_out elif callable(output): # We trust user's size_out if set, because calling output # may have unintended consequences (e.g., network communication) if node.size_out is None: result = self.validate_callable(node, output) node.size_out = 0 if result is None else result.size elif is_array_like(output): # Make into correctly shaped numpy array before validation output = npext.array(output, min_dims=1, copy=False, dtype=np.float64) self.validate_ndarray(node, output) node.size_out = output.size else: raise ValidationError("Invalid node output type %r" % type(output).__name__, attr=self.name, obj=node) # --- Set output self.data[node] = output
def make_step(self, signals, dt, rng): src = signals[self.src] dst = signals[self.dst] src_slice = self.src_slice if self.src_slice is not None else Ellipsis dst_slice = self.dst_slice if self.dst_slice is not None else Ellipsis inc = self.inc # If there are repeated indices in dst_slice, special handling needed. repeats = False if is_array_like(dst_slice): dst_slice = np.array(dst_slice) # copy because we might modify it if dst_slice.dtype.kind != "b": # get canonical, positive indices first dst_slice[dst_slice < 0] += len(dst) repeats = len(np.unique(dst_slice)) < len(dst_slice) if inc and repeats: def step_copy(): np.add.at(dst, dst_slice, src[src_slice]) elif inc: def step_copy(): dst[dst_slice] += src[src_slice] elif repeats: raise BuildError("%s: Cannot have repeated indices in " "``dst_slice`` when copy is not an increment" % self) else: def step_copy(): dst[dst_slice] = src[src_slice] return step_copy
def build_node(model, node): """Builds a `.Node` object into a model. The node build function is relatively simple. It involves creating input and output signals, and connecting them with an `.Operator` that depends on the type of ``node.output``. Parameters ---------- model : Model The model to build into. node : Node The node to build. Notes ----- Sets ``model.params[node]`` to ``None``. """ # input signal if not is_array_like(node.output) and node.size_in > 0: sig_in = Signal(np.zeros(node.size_in), name="%s.in" % node) model.add_op(Reset(sig_in)) else: sig_in = None # Provide output if node.output is None: sig_out = sig_in elif isinstance(node.output, Process): sig_out = Signal(np.zeros(node.size_out), name="%s.out" % node) model.build(node.output, sig_in, sig_out) elif callable(node.output): sig_out = (Signal(np.zeros(node.size_out), name="%s.out" % node) if node.size_out > 0 else None) model.add_op(SimPyFunc( output=sig_out, fn=node.output, t=model.time, x=sig_in)) elif is_array_like(node.output): sig_out = Signal(node.output, name="%s.out" % node) else: raise BuildError( "Invalid node output type %r" % node.output.__class__.__name__) model.sig[node]['in'] = sig_in model.sig[node]['out'] = sig_out model.params[node] = None
def build_node(model, node): """Builds a `.Node` object into a model. The node build function is relatively simple. It involves creating input and output signals, and connecting them with an `.Operator` that depends on the type of ``node.output``. Parameters ---------- model : Model The model to build into. node : Node The node to build. Notes ----- Sets ``model.params[node]`` to ``None``. """ # input signal if not is_array_like(node.output) and node.size_in > 0: sig_in = Signal(np.zeros(node.size_in), name="%s.in" % node) model.add_op(Reset(sig_in)) else: sig_in = None # Provide output if node.output is None: sig_out = sig_in elif isinstance(node.output, Process): sig_out = Signal(np.zeros(node.size_out), name="%s.out" % node) model.build(node.output, sig_in, sig_out) elif callable(node.output): sig_out = (Signal(np.zeros(node.size_out), name="%s.out" % node) if node.size_out > 0 else None) model.add_op( SimPyFunc(output=sig_out, fn=node.output, t=model.time, x=sig_in)) elif is_array_like(node.output): sig_out = Signal(node.output, name="%s.out" % node) else: raise BuildError("Invalid node output type %r" % type(node.output).__name__) model.sig[node]['in'] = sig_in model.sig[node]['out'] = sig_out model.params[node] = None
def dot(self, other): """Return the dot product of the two vectors.""" if isinstance(other, Fixed): infer_types(self, other) other = other.evaluate().v if is_array_like(other): return np.vdot(self.v, other) else: return other.vdot(self)
def assert_is_deepcopy(cp, original): assert cp is not original # ensures separate parameters for param in iter_params(cp): param_inst = getattr(cp, param) if isinstance(param_inst, nengo.solvers.Solver) or isinstance( param_inst, nengo.base.NengoObject): assert_is_copy(param_inst, getattr(original, param)) elif is_array_like(param_inst): assert np.all(param_inst == getattr(original, param)) else: assert param_inst == getattr(original, param)
def __set__(self, conn, function): if function is None: function_info = self.Info(function=None, size=None) elif is_array_like(function): array = np.array(function, copy=False, dtype=np.float64) self.validate_array(conn, array) function_info = self.Info(function=array, size=array.shape[1]) elif callable(function): function_info = self.Info(function=function, size=self.determine_size(conn, function)) self.validate_callable(conn, function_info) else: raise ValidationError("Invalid connection function type %r " "(must be callable or array-like)" % type(function).__name__, attr=self.name, obj=conn) self.validate(conn, function_info) self.data[conn] = function_info
def __set__(self, node, output): super(OutputParam, self).validate(node, output) size_in_set = node.size_in is not None node.size_in = node.size_in if size_in_set else 0 # --- Validate and set the new size_out if output is None: if node.size_out is not None: warnings.warn("'Node.size_out' is being overwritten with " "'Node.size_in' since 'Node.output=None'") node.size_out = node.size_in elif isinstance(output, Process): if not size_in_set: node.size_in = output.default_size_in if node.size_out is None: node.size_out = output.default_size_out elif callable(output): # We trust user's size_out if set, because calling output # may have unintended consequences (e.g., network communication) if node.size_out is None: result = self.validate_callable(node, output) node.size_out = 0 if result is None else result.size elif is_array_like(output): # Make into correctly shaped numpy array before validation output = npext.array(output, min_dims=1, copy=False, dtype=np.float64) self.validate_ndarray(node, output) if not np.all(np.isfinite(output)): raise ValidationError("Output value must be finite.", attr=self.name, obj=node) node.size_out = output.size else: raise ValidationError("Invalid node output type %r" % type(output).__name__, attr=self.name, obj=node) # --- Set output self.data[node] = output
def __set__(self, conn, function): if function is None: function_info = FunctionInfo(function=None, size=None) elif isinstance(function, FunctionInfo): function_info = function elif is_array_like(function): array = np.array(function, copy=False, dtype=np.float64) self.validate_array(conn, array) function_info = FunctionInfo(function=array, size=array.shape[1]) elif callable(function): function_info = FunctionInfo(function=function, size=self.determine_size( conn, function)) self.validate_callable(conn, function_info) else: raise ValidationError("Invalid connection function type %r " "(must be callable or array-like)" % type(function).__name__, attr=self.name, obj=conn) self.validate(conn, function_info) self.data[conn] = function_info
def equal(a, b): if is_array_like(a) or is_array_like(b): return np.array_equal(a, b) else: return a == b
def is_transform_type(transform, types): types = (types, ) if isinstance(types, str) else types assert is_array_like(transform) return "Dense" in types # all old transforms are dense