本文整理汇总了Python中sympy.utilities.iterables.iterable函数的典型用法代码示例。如果您正苦于以下问题:Python iterable函数的具体用法?Python iterable怎么用?Python iterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了iterable函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _initialize_vectors
def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux):
"""Initialize the coordinate and speed vectors."""
none_handler = lambda x: Matrix(x) if x else Matrix()
# Initialize generalized coordinates
q_dep = none_handler(q_dep)
if not iterable(q_ind):
raise TypeError('Generalized coordinates must be an iterable.')
if not iterable(q_dep):
raise TypeError('Dependent coordinates must be an iterable.')
q_ind = Matrix(q_ind)
self._qdep = q_dep
self._q = Matrix([q_ind, q_dep])
self._qdot = self.q.diff(dynamicsymbols._t)
# Initialize generalized speeds
u_dep = none_handler(u_dep)
if not iterable(u_ind):
raise TypeError('Generalized speeds must be an iterable.')
if not iterable(u_dep):
raise TypeError('Dependent speeds must be an iterable.')
u_ind = Matrix(u_ind)
self._udep = u_dep
self._u = Matrix([u_ind, u_dep])
self._udot = self.u.diff(dynamicsymbols._t)
self._uaux = none_handler(u_aux)
示例2: _contains
def _contains(self, other):
from sympy.matrices import Matrix
from sympy.solvers.solveset import solveset, linsolve
from sympy.utilities.iterables import iterable, cartes
L = self.lamda
if self._is_multivariate():
if not iterable(L.expr):
if iterable(other):
return S.false
return other.as_numer_denom() in self.func(
Lambda(L.variables, L.expr.as_numer_denom()), self.base_set)
if len(L.expr) != len(self.lamda.variables):
raise NotImplementedError(filldedent('''
Dimensions of input and output of Lambda are different.'''))
eqs = [expr - val for val, expr in zip(other, L.expr)]
variables = L.variables
free = set(variables)
if all(i.is_number for i in list(Matrix(eqs).jacobian(variables))):
solns = list(linsolve([e - val for e, val in
zip(L.expr, other)], variables))
else:
syms = [e.free_symbols & free for e in eqs]
solns = {}
for i, (e, s, v) in enumerate(zip(eqs, syms, other)):
if not s:
if e != v:
return S.false
solns[vars[i]] = [v]
continue
elif len(s) == 1:
sy = s.pop()
sol = solveset(e, sy)
if sol is S.EmptySet:
return S.false
elif isinstance(sol, FiniteSet):
solns[sy] = list(sol)
else:
raise NotImplementedError
else:
raise NotImplementedError
solns = cartes(*[solns[s] for s in variables])
else:
# assume scalar -> scalar mapping
solnsSet = solveset(L.expr - other, L.variables[0])
if solnsSet.is_FiniteSet:
solns = list(solnsSet)
else:
raise NotImplementedError(filldedent('''
Determining whether an ImageSet contains %s has not
been implemented.''' % func_name(other)))
for soln in solns:
try:
if soln in self.base_set:
return S.true
except TypeError:
return self.base_set.contains(soln.evalf())
return S.false
示例3: __new__
def __new__(cls, target, iter, body):
target = _sympify(target)
if not iterable(iter):
raise TypeError("iter must be an iterable")
iter = _sympify(iter)
if not iterable(body):
raise TypeError("body must be an iterable")
body = Tuple(*(_sympify(i) for i in body))
return Basic.__new__(cls, target, iter, body)
示例4: partial_velocity
def partial_velocity(vel_vecs, gen_speeds, frame):
"""Returns a list of partial velocities with respect to the provided
generalized speeds in the given reference frame for each of the supplied
velocity vectors.
The output is a list of lists. The outer list has a number of elements
equal to the number of supplied velocity vectors. The inner lists are, for
each velocity vector, the partial derivatives of that velocity vector with
respect to the generalized speeds supplied.
Parameters
==========
vel_vecs : iterable
An iterable of velocity vectors (angular or linear).
gen_speeds : iterable
An iterable of generalized speeds.
frame : ReferenceFrame
The reference frame that the partial derivatives are going to be taken
in.
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import partial_velocity
>>> u = dynamicsymbols('u')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, u * N.x)
>>> vel_vecs = [P.vel(N)]
>>> gen_speeds = [u]
>>> partial_velocity(vel_vecs, gen_speeds, N)
[[N.x]]
"""
if not iterable(vel_vecs):
raise TypeError('Velocity vectors must be contained in an iterable.')
if not iterable(gen_speeds):
raise TypeError('Generalized speeds must be contained in an iterable')
vec_partials = []
for vec in vel_vecs:
partials = []
for speed in gen_speeds:
partials.append(vec.diff(speed, frame, var_in_dcm=False))
vec_partials.append(partials)
return vec_partials
示例5: __new__
def __new__(cls, target, iter, body):
target = _sympify(target)
if not iterable(iter):
raise TypeError("iter must be an iterable")
if isinstance(iter, list):
# _sympify errors on lists because they are mutable
iter = tuple(iter)
iter = _sympify(iter)
if not isinstance(body, CodeBlock):
if not iterable(body):
raise TypeError("body must be an iterable or CodeBlock")
body = CodeBlock(*(_sympify(i) for i in body))
return Basic.__new__(cls, target, iter, body)
示例6: partial_velocity
def partial_velocity(vel_list, u_list, frame):
"""Returns a list of partial velocities.
For a list of velocity or angular velocity vectors the partial derivatives
with respect to the supplied generalized speeds are computed, in the
specified ReferenceFrame.
The output is a list of lists. The outer list has a number of elements
equal to the number of supplied velocity vectors. The inner lists are, for
each velocity vector, the partial derivatives of that velocity vector with
respect to the generalized speeds supplied.
Parameters
==========
vel_list : list
List of velocities of Point's and angular velocities of ReferenceFrame's
u_list : list
List of independent generalized speeds.
frame : ReferenceFrame
The ReferenceFrame the partial derivatives are going to be taken in.
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import partial_velocity
>>> u = dynamicsymbols('u')
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, u * N.x)
>>> vel_list = [P.vel(N)]
>>> u_list = [u]
>>> partial_velocity(vel_list, u_list, N)
[[N.x]]
"""
if not iterable(vel_list):
raise TypeError('Provide velocities in an iterable')
if not iterable(u_list):
raise TypeError('Provide speeds in an iterable')
list_of_pvlists = []
for i in vel_list:
pvlist = []
for j in u_list:
vel = i.diff(j, frame)
pvlist += [vel]
list_of_pvlists += [pvlist]
return list_of_pvlists
示例7: dynamicsymbols
def dynamicsymbols(names, level=0):
"""Uses symbols and Function for functions of time.
Creates a SymPy UndefinedFunction, which is then initialized as a function
of a variable, the default being Symbol('t').
Parameters
==========
names : str
Names of the dynamic symbols you want to create; works the same way as
inputs to symbols
level : int
Level of differentiation of the returned function; d/dt once of t,
twice of t, etc.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy import diff, Symbol
>>> q1 = dynamicsymbols('q1')
>>> q1
q1(t)
>>> diff(q1, Symbol('t'))
Derivative(q1(t), t)
"""
esses = symbols(names, cls=Function)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, [t] * level, e(t)) for e in esses]
return esses
else:
return reduce(diff, [t] * level, esses(t))
示例8: _form_fr
def _form_fr(self, fl):
"""Form the generalized active force."""
if fl != None and (len(fl) == 0 or not iterable(fl)):
raise ValueError('Force pairs must be supplied in an '
'non-empty iterable or None.')
N = self._inertial
# pull out relevant velocities for constructing partial velocities
vel_list, f_list = _f_list_parser(fl, N)
vel_list = [msubs(i, self._qdot_u_map) for i in vel_list]
# Fill Fr with dot product of partial velocities and forces
o = len(self.u)
b = len(f_list)
FR = zeros(o, 1)
partials = partial_velocity(vel_list, self.u, N)
for i in range(o):
FR[i] = sum(partials[j][i] & f_list[j] for j in range(b))
# In case there are dependent speeds
if self._udep:
p = o - len(self._udep)
FRtilde = FR[:p, 0]
FRold = FR[p:o, 0]
FRtilde += self._Ars.T * FRold
FR = FRtilde
self._forcelist = fl
self._fr = FR
return FR
示例9: dimension
def dimension(*args):
""" Creates a 'dimension' Attribute with (up to 7) extents.
Examples
========
>>> from sympy.printing import fcode
>>> from sympy.codegen.fnodes import dimension, intent_in
>>> dim = dimension('2', ':') # 2 rows, runtime determined number of columns
>>> from sympy.codegen.ast import Variable, integer
>>> arr = Variable('a', integer, attrs=[dim, intent_in])
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
'integer*4, dimension(2, :), intent(in) :: a'
"""
if len(args) > 7:
raise ValueError("Fortran only supports up to 7 dimensional arrays")
parameters = []
for arg in args:
if isinstance(arg, Extent):
parameters.append(arg)
elif isinstance(arg, string_types):
if arg == ':':
parameters.append(Extent())
else:
parameters.append(String(arg))
elif iterable(arg):
parameters.append(Extent(*arg))
else:
parameters.append(sympify(arg))
if len(args) == 0:
raise ValueError("Need at least one dimension")
return Attribute('dimension', parameters)
示例10: find_dynamicsymbols
def find_dynamicsymbols(expression, exclude=None):
"""Find all dynamicsymbols in expression.
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
set([x(t), y(t), Derivative(x(t), t)])
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
>>> find_dynamicsymbols(expr, [x, y])
set([Derivative(x(t), t)])
"""
t_set = set([dynamicsymbols._t])
if exclude:
if iterable(exclude):
exclude_set = set(exclude)
else:
raise TypeError("exclude kwarg must be iterable")
else:
exclude_set = set()
return set([i for i in expression.atoms(AppliedUndef, Derivative) if
i.free_symbols == t_set]) - exclude_set
示例11: __new__
def __new__(cls, name, body):
if not isinstance(name, str):
raise TypeError("Module name must be string")
name = Symbol(name)
# body
if not iterable(body):
raise TypeError("body must be an iterable")
body = Tuple(*body)
return Basic.__new__(cls, name, body)
示例12: __new__
def __new__(cls, name, args, results):
# name
if isinstance(name, str):
name = Symbol(name)
elif not isinstance(name, Symbol):
raise TypeError("Function name must be Symbol or string")
# args
if not iterable(args):
raise TypeError("args must be an iterable")
if not all(isinstance(a, Argument) for a in args):
raise TypeError("All args must be of type Argument")
args = Tuple(*args)
# results
if not iterable(results):
raise TypeError("results must be an iterable")
if not all(isinstance(i, RoutineResult) for i in results):
raise TypeError("All results must be of type RoutineResult")
results = Tuple(*results)
return Basic.__new__(cls, name, args, results)
示例13: __new__
def __new__(cls, *args):
if len(args)==1 and args[0].__class__ is dict:
items = [Tuple(k, v) for k, v in args[0].iteritems()]
elif iterable(args) and all(len(arg) == 2 for arg in args):
items = [Tuple(k, v) for k, v in args]
else:
raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
obj = Basic.__new__(cls, *items)
obj._dict = dict(items) # In case Tuple decides it wants to sympify
return obj
示例14: find_dynamicsymbols
def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
"""Find all dynamicsymbols in expression.
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
If we intend to apply this function on a vector, the optional
''reference_frame'' is also used to inform about the corresponding frame
with respect to which the dynamic symbols of the given vector is to be
determined.
Parameters
==========
expression : sympy expression
exclude : iterable of dynamicsymbols, optional
reference_frame : ReferenceFrame, optional
The frame with respect to which the dynamic symbols of the
given vector is to be determined.
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> from sympy.physics.mechanics import ReferenceFrame
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
{x(t), y(t), Derivative(x(t), t)}
>>> find_dynamicsymbols(expr, exclude=[x, y])
{Derivative(x(t), t)}
>>> a, b, c = dynamicsymbols('a, b, c')
>>> A = ReferenceFrame('A')
>>> v = a * A.x + b * A.y + c * A.z
>>> find_dynamicsymbols(v, reference_frame=A)
{a(t), b(t), c(t)}
"""
t_set = {dynamicsymbols._t}
if exclude:
if iterable(exclude):
exclude_set = set(exclude)
else:
raise TypeError("exclude kwarg must be iterable")
else:
exclude_set = set()
if isinstance(expression, Vector):
if reference_frame is None:
raise ValueError("You must provide reference_frame when passing a "
"vector expression, got %s." % reference_frame)
else:
expression = expression.to_matrix(reference_frame)
return set([i for i in expression.atoms(AppliedUndef, Derivative) if
i.free_symbols == t_set]) - exclude_set
示例15: __new__
def __new__(cls, *args):
if len(args) == 1 and isinstance(args[0], (dict, Dict)):
items = [Tuple(k, v) for k, v in args[0].items()]
elif iterable(args) and all(len(arg) == 2 for arg in args):
items = [Tuple(k, v) for k, v in args]
else:
raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
elements = frozenset(items)
obj = Basic.__new__(cls, elements)
obj.elements = elements
obj._dict = dict(items) # In case Tuple decides it wants to sympify
return obj