本文整理汇总了Python中nengo.utils.compat.is_number函数的典型用法代码示例。如果您正苦于以下问题:Python is_number函数的具体用法?Python is_number怎么用?Python is_number使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_number函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scalar_value
def scalar_value(self):
if is_number(self.value):
return self.value
elif self.neutral or self.value == "":
return 0.0
else:
return 1.0
示例2: parse
def parse(self, text):
"""Evaluate a text string and return the corresponding SemanticPointer.
This uses the Python ``eval()`` function, so any Python operators that
have been defined for SemanticPointers are valid (``+``, ``-``, ``*``,
``~``, ``()``). Any terms do not exist in the vocabulary will be
automatically generated. Valid semantic pointer terms must start
with a capital letter.
If the expression returns a scalar (int or float), a scaled version
of the identity SemanticPointer will be returned.
"""
# The following line does everything. Note that self is being
# passed in as the locals dictionary, and thanks to the __getitem__
# implementation, this will automatically create new semantic
# pointers as needed.
try:
value = eval(text, {}, self)
except NameError:
raise SpaParseError(
"Semantic pointers must start with a capital letter.")
if is_number(value):
value = value * self.identity
if not isinstance(value, pointer.SemanticPointer):
raise SpaParseError(
"The result of parsing '%s' is not a SemanticPointer" % text)
return value
示例3: build_nrn_connection
def build_nrn_connection(model, conn):
# Create random number generator
rng = np.random.RandomState(model.seeds[conn])
# Check pre-conditions
assert isinstance(conn.pre, nengo.Ensemble)
assert not isinstance(conn.pre.neuron_type, nengo.neurons.Direct)
# FIXME assert no rate neurons are used. How to do that?
# Get input signal
# FIXME this should probably be
# model.sig[conn]['in'] = model.sig[conn.pre]["out"]
# in both cases
if isinstance(conn.pre, nengo.ensemble.Neurons):
model.sig[conn]["in"] = model.sig[conn.pre.ensemble]["out"]
else:
model.sig[conn]["in"] = model.sig[conn.pre]["out"]
# Figure out type of connection
if isinstance(conn.post, nengo.ensemble.Neurons):
raise NotImplementedError() # TODO
elif isinstance(conn.post.neuron_type, Compartmental):
pass
else:
raise AssertionError("This function should only be called if post neurons are " "compartmental.")
# Solve for weights
# FIXME just assuming solver is a weight solver, may that break?
# Default solver should probably also produce sparse solutions for
# performance reasons
eval_points, activities, targets = build_linear_system(model, conn, rng=rng)
# account for transform
transform = full_transform(conn)
targets = np.dot(targets, transform.T)
weights, solver_info = conn.solver(activities, targets, rng=rng, E=model.params[conn.post].scaled_encoders.T)
# Synapse type
synapse = conn.synapse
if is_number(synapse):
synapse = ExpSyn(synapse)
# Connect
# TODO: Why is this adjustment of the weights necessary?
weights = weights / synapse.tau / 5.0 * 0.1
connections = [[] for i in range(len(weights))]
for i, cell in enumerate(ens_to_cells[conn.post]):
for j, w in enumerate(weights[:, i]):
if w >= 0.0:
x = np.random.rand()
connections[j].append(synapse.create(cell.neuron.apical(x), w * (x + 1)))
else:
connections[j].append(synapse.create(cell.neuron.soma(0.5), w))
# 3. Add operator creating events for synapses if pre neuron fired
model.add_op(NrnTransmitSpikes(model.sig[conn]["in"], connections))
示例4: validate
def validate(self, instance, num):
if num is not None:
if not is_number(num):
raise ValueError("Must be a number; got '%s'" % num)
if self.low is not None and num < self.low:
raise ValueError("Number must be greater than %s" % self.low)
if self.high is not None and num > self.high:
raise ValueError("Number must be less than %s" % self.high)
super(NumberParam, self).validate(instance, num)
示例5: filtered_signal
def filtered_signal(model, owner, sig, synapse):
# Note: we add a filter here even if synapse < dt,
# in order to avoid cycles in the op graph. If the filter
# is explicitly set to None (e.g. for a passthrough node)
# then cycles can still occur.
if is_number(synapse):
synapse = Lowpass(synapse)
assert isinstance(synapse, Synapse)
model.build(synapse, owner, sig)
return model.sig[owner]['synapse_out']
示例6: __rmul__
def __rmul__(self, other):
"""Multiplication of two SemanticPointers is circular convolution.
If mutliplied by a scaler, we do normal multiplication.
"""
if isinstance(other, SemanticPointer):
return self.convolve(other)
elif is_number(other):
return SemanticPointer(data=self.v * other)
else:
raise Exception('Can only multiply by SemanticPointers or scalars')
示例7: _parse_var
def _parse_var(self, var):
if is_number(var):
return NumExp(var)
elif isinstance(var, str):
return '"%s"' % var
elif isinstance(var, (list, np.ndarray)):
if isinstance(var, np.ndarray):
var = var.tolist()
self._check_vector_length(len(var))
return [self._parse_var(v) for v in var]
else:
return var
示例8: __mul__
def __mul__(self, other):
"""Multiplication of two SemanticPointers is circular convolution.
If multiplied by a scalar, we do normal multiplication.
"""
if isinstance(other, SemanticPointer):
return self.convolve(other)
elif is_number(other):
return SemanticPointer(data=self.v * other)
else:
raise NotImplementedError(
"Can only multiply by SemanticPointers or scalars")
示例9: validate
def validate(self, instance, num):
if num is not None:
if not is_number(num):
raise ValueError("Must be a number; got '%s'" % num)
low_comp = 0 if self.low_open else -1
if self.low is not None and compare(num, self.low) <= low_comp:
raise ValueError("Value must be greater than %s%s (got %s)" % (
"" if self.low_open else "or equal to ", self.low, num))
high_comp = 0 if self.high_open else 1
if self.high is not None and compare(num, self.high) >= high_comp:
raise ValueError("Value must be less than %s%s (got %s)" % (
"" if self.high_open else "or equal to ", self.high, num))
super(NumberParam, self).validate(instance, num)
示例10: __imul__
def __imul__(self, other):
"""Multiplication of two SemanticPointers is circular convolution.
If mutliplied by a scaler, we do normal multiplication.
"""
if isinstance(other, SemanticPointer):
self.v = np.fft.ifft(np.fft.fft(self.v) *
np.fft.fft(other.v)).real
elif is_number(other):
self.v *= other
else:
raise Exception('Can only multiply by SemanticPointers or scalars')
return self
示例11: __mul__
def __mul__(self, other):
if isinstance(other, Symbol):
if other.symbol == '1':
return self
if self.symbol == '1':
return other
return Symbol('(%s * %s)' % (self.symbol, other.symbol))
if is_number(other):
if other == 1:
return self
if self.symbol == '1':
return Symbol('%g' % other)
return Symbol('(%s * %g)' % (self.symbol, other))
return NotImplemented
示例12: on_add
def on_add(self, spa):
"""Form the connections into the BG to compute the utilty values.
Each action's condition variable contains the set of computations
needed for that action's utility value, which is the input to the
basal ganglia.
"""
Module.on_add(self, spa)
self.spa = spa
self.actions.process(spa) # parse the actions
for i, action in enumerate(self.actions.actions):
cond = action.condition.expression
# the basal ganglia hangles the condition part of the action;
# the effect is handled by the thalamus
# Note: A Source is an output from a module, and a Symbol is
# text that can be parsed to be a SemanticPointer
for c in cond.items:
if isinstance(c, DotProduct):
if ((isinstance(c.item1, Source) and c.item1.inverted) or
(isinstance(c.item2, Source) and c.item2.inverted)):
raise NotImplementedError(
"Inversion in subexpression '%s' from action '%s' "
"is not supported by the Basal Ganglia." %
(c, action))
if isinstance(c.item1, Source):
if isinstance(c.item2, Source):
# dot product between two different sources
self.add_compare_input(i, c.item1, c.item2,
c.scale)
else:
self.add_dot_input(i, c.item1, c.item2, c.scale)
else:
# enforced in DotProduct constructor
assert isinstance(c.item2, Source)
self.add_dot_input(i, c.item2, c.item1, c.scale)
elif isinstance(c, Source):
self.add_scalar_input(i, c)
elif is_number(c):
self.add_bias_input(i, c)
else:
raise NotImplementedError(
"Subexpression '%s' from action '%s' is not supported "
"by the Basal Ganglia." % (c, action))
示例13: _sys2form
def _sys2form(sys):
if isinstance(sys, LinearSystem):
return _LSYS
elif isinstance(sys, LinearFilter):
return _LFILT
elif is_number(sys):
return _NUM
elif len(sys) == 2:
return _TF
elif len(sys) == 3:
return _ZPK
elif len(sys) == 4:
return _SS
else:
raise ValueError(
"sys must be an instance of LinearSystem, a scalar, or a tuple of "
"2 (tf), 3 (zpk), or 4 (ss) arrays.")
示例14: filt
def filt(signal, synapse, dt, axis=0, x0=None, copy=True):
"""Filter ``signal`` with ``synapse``.
Parameters
----------
signal : array_like
The signal to filter.
syanpse : float, Synapse
The synapse model with which to filter the signal.
If a float is passed in, it will be interpreted as the ``tau``
parameter of a lowpass filter.
axis : integer, optional
The axis along which to filter. Default: 0.
x0 : array_like, optional
The starting state of the filter output.
copy : boolean, optional
Whether to copy the input data, or simply work in-place. Default: True.
"""
if is_number(synapse):
synapse = Lowpass(synapse)
filtered = np.array(signal, copy=copy)
filt_view = np.rollaxis(filtered, axis=axis) # rolled view on filtered
# --- buffer method
if x0 is not None:
if x0.shape != filt_view[0].shape:
raise ValueError("'x0' with shape %s must have shape %s" %
(x0.shape, filt_view[0].shape))
signal_out = np.array(x0)
else:
# signal_out is our buffer for the current filter state
signal_out = np.zeros_like(filt_view[0])
step = synapse.make_step(dt, signal_out)
for i, signal_in in enumerate(filt_view):
step(signal_in)
filt_view[i] = signal_out
return filtered
示例15: filtfilt
def filtfilt(signal, synapse, dt, axis=0, copy=True):
"""Zero-phase filtering of ``signal`` using the ``syanpse`` filter.
This is done by filtering the input in forward and reverse directions.
Equivalent to scipy and Matlab's filtfilt function using the filter
defined by the synapse object passed in.
Parameters
----------
signal : array_like
The signal to filter.
synapse : float, Synapse
The synapse model with which to filter the signal.
If a float is passed in, it will be interpreted as the ``tau``
parameter of a lowpass filter.
axis : integer, optional
The axis along which to filter. Default: 0.
copy : boolean, optional
Whether to copy the input data, or simply work in-place. Default: True.
"""
if is_number(synapse):
synapse = Lowpass(synapse)
filtered = np.array(signal, copy=copy)
filt_view = np.rollaxis(filtered, axis=axis)
signal_out = np.zeros_like(filt_view[0])
step = synapse.make_step(dt, signal_out)
for i, signal_in in enumerate(filt_view):
step(signal_in)
filt_view[i] = signal_out
# Flip the filt_view and filter again
filt_view = filt_view[::-1]
for i, signal_in in enumerate(filt_view):
step(signal_in)
filt_view[i] = signal_out
return filtered