本文整理汇总了Python中mathics.core.expression.Expression.get_head_name方法的典型用法代码示例。如果您正苦于以下问题:Python Expression.get_head_name方法的具体用法?Python Expression.get_head_name怎么用?Python Expression.get_head_name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mathics.core.expression.Expression
的用法示例。
在下文中一共展示了Expression.get_head_name方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testInverseConversions
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def testInverseConversions(self):
# check that a conversion A -> B -> A restores the original
# components. this tests color space transformations and their
# inverse transformations.
def space_to_head(name):
if name == 'HSB':
return 'System`Hue'
else:
return 'System`%sColor' % name
spaces = ("CMYK", "HSB", "LAB", "LCH", "LUV", "RGB", "XYZ")
places = 3
for original in ((0.5, 0.1, 0.2), (0.9, 0.1, 0.1)):
for i, from_space in enumerate(spaces):
for to_space in spaces[i + 1:]:
try:
construct_name = space_to_head(from_space)
source_color = Expression(construct_name, *original)
# now calculate from_space -> to_space -> from_space
target_color = Expression('ColorConvert', source_color, to_space).evaluate(self.evaluation)
self.assertEqual(target_color.get_head_name(), space_to_head(to_space))
checked_color = Expression('ColorConvert', target_color, from_space).evaluate(self.evaluation)
self.assertEqual(checked_color.get_head_name(), source_color.get_head_name())
checked_components = [c.to_python() for c in checked_color.leaves]
if from_space == 'CMYK': # if cmyk, cmyk -> cmy
k = checked_components[3]
checked_components = [c * (1 - k) + k for c in checked_components[:3]]
self.assertEqual(len(original), len(checked_components))
for x, y in zip(original, checked_components):
self.assertAlmostEqual(x, y, places)
except:
print('test failed for %s -> %s -> %s' %
(_color_string(from_space, original), to_space, from_space))
raise
示例2: add
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def add(self, expression, evaluation):
expr = Expression('System`Private`ManipulateParameter', expression).evaluate(evaluation)
if expr.get_head_name() != 'System`List': # if everything was parsed ok, we get a List
return False
# convert the rules given us by ManipulateParameter[] into a dict. note: duplicate keys
# will be overwritten, the latest one wins.
kwargs = {'evaluation': evaluation}
for rule in expr.leaves:
if rule.get_head_name() != 'System`Rule' or len(rule.leaves) != 2:
return False
kwargs[strip_context(rule.leaves[0].to_python()).lower()] = rule.leaves[1]
widget = kwargs['type'].get_string_value()
del kwargs['type']
getattr(self, '_add_%s_widget' % widget.lower())(**kwargs) # create the widget
return True
示例3: get_results
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def get_results(tmp_function):
if function_channels == Expression('List', String('FileNames')):
tmp = Expression(tmp_function, findfile).evaluate(evaluation)
elif function_channels == Expression('List', String('Streams')):
stream = Expression('OpenRead', findfile).evaluate(evaluation)
if stream.get_head_name() != 'InputStream':
evaluation.message('Import', 'nffil')
return None
tmp = Expression(tmp_function, stream).evaluate(evaluation)
Expression('Close', stream).evaluate(evaluation)
else:
#TODO print appropriate error message
raise NotImplementedError
tmp = tmp.get_leaves()
if not all(expr.has_form('Rule', None) for expr in tmp):
return None
# return {a.get_string_value() : b for (a,b) in map(lambda x: x.get_leaves(), tmp)}
return dict((a.get_string_value(), b) for (a,b) in map(lambda x: x.get_leaves(), tmp))
示例4: apply
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def apply(self, l, f, evaluation):
'SortBy[l_, f_]'
if l.is_atom():
return evaluation.message('Sort', 'normal')
elif l.get_head_name() != 'System`List':
expr = Expression('SortBy', l, f)
return evaluation.message(self.get_name(), 'list', expr, 1)
else:
keys_expr = Expression('Map', f, l).evaluate(evaluation) # precompute:
# even though our sort function has only (n log n) comparisons, we should
# compute f no more than n times.
if keys_expr is None or keys_expr.get_head_name() != 'System`List'\
or len(keys_expr.leaves) != len(l.leaves):
expr = Expression('SortBy', l, f)
return evaluation.message('SortBy', 'func', expr, 2)
keys = keys_expr.leaves
raw_keys = l.leaves
class Key(object):
def __init__(self, index):
self.index = index
def __gt__(self, other):
kx, ky = keys[self.index], keys[other.index]
if kx > ky:
return True
elif kx < ky:
return False
else: # if f(x) == f(y), resort to x < y?
return raw_keys[self.index] > raw_keys[other.index]
# we sort a list of indices. after sorting, we reorder the leaves.
new_indices = sorted(list(range(len(raw_keys))), key=Key)
new_leaves = [raw_keys[i] for i in new_indices] # reorder leaves
return Expression(l.head, *new_leaves)
示例5: apply
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def apply(self, eqns, a, n, evaluation):
'RSolve[eqns_, a_, n_]'
# TODO: Do this with rules?
if not eqns.has_form('List', None):
eqns = Expression('List', eqns)
if len(eqns.leaves) == 0:
return
for eqn in eqns.leaves:
if eqn.get_head_name() != 'System`Equal':
evaluation.message('RSolve', 'deqn', eqn)
return
if (n.is_atom() and not n.is_symbol()) or \
n.get_head_name() in ('System`Plus', 'System`Times',
'System`Power') or \
'System`Constant' in n.get_attributes(evaluation.definitions):
# TODO: Factor out this check for dsvar into a separate
# function. DSolve uses this too.
evaluation.message('RSolve', 'dsvar')
return
try:
a.leaves
function_form = None
func = a
except AttributeError:
func = Expression(a, n)
function_form = Expression('List', n)
if func.is_atom() or len(func.leaves) != 1:
evaluation.message('RSolve', 'dsfun', a)
if n not in func.leaves:
evaluation.message('DSolve', 'deqx')
# Seperate relations from conditions
conditions = {}
def is_relation(eqn):
left, right = eqn.leaves
for l, r in [(left, right), (right, left)]:
if (left.get_head_name() == func.get_head_name() and # noqa
len(left.leaves) == 1 and
isinstance(l.leaves[0].to_python(), int) and
r.is_numeric()):
conditions[l.leaves[0].to_python()] = r.to_sympy()
return False
return True
relation = filter(is_relation, eqns.leaves)[0]
left, right = relation.leaves
relation = Expression('Plus', left, Expression(
'Times', -1, right)).evaluate(evaluation)
sym_eq = relation.to_sympy(
converted_functions=set([func.get_head_name()]))
sym_n = sympy.symbols(str(sympy_symbol_prefix + n.name))
sym_func = sympy.Function(str(
sympy_symbol_prefix + func.get_head_name()))(sym_n)
sym_conds = {}
for cond in conditions:
sym_conds[sympy.Function(str(
sympy_symbol_prefix + func.get_head_name()))(cond)] = \
conditions[cond]
try:
# Sympy raises error when given empty conditions. Fixed in
# upcomming sympy release.
if sym_conds != {}:
sym_result = sympy.rsolve(sym_eq, sym_func, sym_conds)
else:
sym_result = sympy.rsolve(sym_eq, sym_func)
if not isinstance(sym_result, list):
sym_result = [sym_result]
except ValueError:
return
if function_form is None:
return Expression('List', *[
Expression('List', Expression('Rule', a, from_sympy(soln)))
for soln in sym_result])
else:
return Expression('List', *[
Expression('List', Expression(
'Rule', a, Expression('Function', function_form,
from_sympy(soln)))) for soln in sym_result])
示例6: apply
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def apply(self, eqn, y, x, evaluation):
'DSolve[eqn_, y_, x_]'
if eqn.has_form('List', eqn):
#TODO: Try and solve BVPs using Solve or something analagous OR add this functonality to sympy.
evaluation.message('DSolve', 'symsys')
return
if eqn.get_head_name() != 'Equal':
evaluation.message('DSolve', 'deqn', eqn)
return
if (x.is_atom() and not x.is_symbol()) or \
x.get_head_name() in ('Plus', 'Times', 'Power') or \
'Constant' in x.get_attributes(evaluation.definitions):
evaluation.message('DSolve', 'dsvar')
return
# Fixes pathalogical DSolve[y''[x] == y[x], y, x]
try:
y.leaves
function_form = None
func = y
except AttributeError:
func = Expression(y, x)
function_form = Expression('List', x)
if func.is_atom():
evaluation.message('DSolve', 'dsfun', y)
return
if len(func.leaves) != 1:
evaluation.message('DSolve', 'symmua')
return
if x not in func.leaves:
evaluation.message('DSolve', 'deqx')
return
left, right = eqn.leaves
eqn = Expression('Plus', left, Expression('Times', -1, right)).evaluate(evaluation)
sym_eq = eqn.to_sympy(converted_functions = set([func.get_head_name()]))
sym_x = sympy.symbols(str(sympy_symbol_prefix + x.name))
sym_func = sympy.Function(str(sympy_symbol_prefix + func.get_head_name())) (sym_x)
try:
sym_result = sympy.dsolve(sym_eq, sym_func)
if not isinstance(sym_result, list):
sym_result = [sym_result]
except ValueError as e:
evaluation.message('DSolve', 'symimp')
return
except NotImplementedError as e:
evaluation.message('DSolve', 'symimp')
return
except AttributeError as e:
evaluation.message('DSolve', 'litarg', eqn)
return
except KeyError:
evaluation.message('DSolve', 'litarg', eqn)
return
if function_form is None:
return Expression('List', *[Expression('List',
Expression('Rule', *from_sympy(soln).leaves)) for soln in sym_result])
else:
return Expression('List', *[Expression('List', Expression('Rule', y,
Expression('Function', function_form, *from_sympy(soln).leaves[1:]))) for soln in sym_result])
示例7: apply
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def apply(self, eqn, y, x, evaluation):
"DSolve[eqn_, y_, x_]"
if eqn.has_form("List", eqn):
# TODO: Try and solve BVPs using Solve or something analagous OR
# add this functonality to sympy.
evaluation.message("DSolve", "symsys")
return
if eqn.get_head_name() != "Equal":
evaluation.message("DSolve", "deqn", eqn)
return
if (
(x.is_atom() and not x.is_symbol())
or x.get_head_name() in ("Plus", "Times", "Power") # nopep8
or "Constant" in x.get_attributes(evaluation.definitions)
):
evaluation.message("DSolve", "dsvar")
return
# Fixes pathalogical DSolve[y''[x] == y[x], y, x]
try:
y.leaves
function_form = None
func = y
except AttributeError:
func = Expression(y, x)
function_form = Expression("List", x)
if func.is_atom():
evaluation.message("DSolve", "dsfun", y)
return
if len(func.leaves) != 1:
evaluation.message("DSolve", "symmua")
return
if x not in func.leaves:
evaluation.message("DSolve", "deqx")
return
left, right = eqn.leaves
eqn = Expression("Plus", left, Expression("Times", -1, right)).evaluate(evaluation)
sym_eq = eqn.to_sympy(converted_functions=set([func.get_head_name()]))
sym_x = sympy.symbols(str(sympy_symbol_prefix + x.name))
sym_func = sympy.Function(str(sympy_symbol_prefix + func.get_head_name()))(sym_x)
try:
sym_result = sympy.dsolve(sym_eq, sym_func)
if not isinstance(sym_result, list):
sym_result = [sym_result]
except ValueError:
evaluation.message("DSolve", "symimp")
return
except NotImplementedError:
evaluation.message("DSolve", "symimp")
return
except AttributeError:
evaluation.message("DSolve", "litarg", eqn)
return
except KeyError:
evaluation.message("DSolve", "litarg", eqn)
return
if function_form is None:
return Expression(
"List", *[Expression("List", Expression("Rule", *from_sympy(soln).leaves)) for soln in sym_result]
)
else:
return Expression(
"List",
*[
Expression(
"List",
Expression("Rule", y, Expression("Function", function_form, *from_sympy(soln).leaves[1:])),
)
for soln in sym_result
]
)
示例8: apply
# 需要导入模块: from mathics.core.expression import Expression [as 别名]
# 或者: from mathics.core.expression.Expression import get_head_name [as 别名]
def apply(self, eqn, y, x, evaluation):
'DSolve[eqn_, y_, x_]'
if eqn.has_form('List', None):
# TODO: Try and solve BVPs using Solve or something analagous OR
# add this functonality to sympy.
evaluation.message('DSolve', 'symsys')
return
if eqn.get_head_name() != 'System`Equal':
evaluation.message('DSolve', 'deqn', eqn)
return
if x.is_symbol():
syms = [x]
elif x.has_form('List', 1, None):
syms = x.get_leaves()
else:
return evaluation.message('DSolve', 'dsvar', x)
# Fixes pathalogical DSolve[y''[x] == y[x], y, x]
try:
y.leaves
function_form = None
func = y
except AttributeError:
func = Expression(y, *syms)
function_form = Expression('List', *syms)
if func.is_atom():
evaluation.message('DSolve', 'dsfun', y)
return
if set(func.leaves) != set(syms):
evaluation.message('DSolve', 'deqx')
return
# Workaround sympy bug #11669.
# https://github.com/sympy/sympy/issues/11669https://github.com/sympy/sympy/issues/11669
f_name = func.get_head_name()
if six.PY2:
try:
f_name = str(f_name)
except UnicodeEncodeError:
return evaluation.message('DSolve', 'sym11669', func.get_head_name())
conversion_args = {'converted_functions': set([f_name])}
sym_func = func.to_sympy(**conversion_args)
sym_eq = eqn.to_sympy(**conversion_args)
# XXX when sympy adds support for higher-order PDE we will have to
# change this to a tuple of solvefuns
kwargs = {'solvefun': sympy.Function(str('C1'))}
try:
if len(syms) > 1:
sym_result = sympy.pdsolve(sym_eq, sym_func, **kwargs)
else:
sym_result = sympy.dsolve(sym_eq, sym_func)
except ValueError:
evaluation.message('DSolve', 'symimp')
return
except NotImplementedError:
evaluation.message('DSolve', 'symimp')
return
except TypeError:
# Sympy bug #9446
evaluation.message('DSolve', 'litarg', eqn)
return
except AttributeError:
evaluation.message('DSolve', 'litarg', eqn)
return
except KeyError:
evaluation.message('DSolve', 'litarg', eqn)
return
else:
if not isinstance(sym_result, list):
sym_result = [sym_result]
if function_form is None:
return Expression('List', *[
Expression(
'List', Expression('Rule', *from_sympy(soln).leaves))
for soln in sym_result])
else:
return Expression('List', *[
Expression('List', Expression('Rule', y, Expression(
'Function', function_form, *from_sympy(soln).leaves[1:])))
for soln in sym_result])