本文整理汇总了Python中mathics.core.expression.from_python函数的典型用法代码示例。如果您正苦于以下问题:Python from_python函数的具体用法?Python from_python怎么用?Python from_python使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了from_python函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply_makeboxes
def apply_makeboxes(self, expr, n, f, evaluation):
'''MakeBoxes[BaseForm[expr_, n_],
f:StandardForm|TraditionalForm|OutputForm]'''
base = n.get_int_value()
if base <= 0:
evaluation.message('BaseForm', 'intpm', expr, n)
return
if not (isinstance(expr, Integer) or isinstance(expr, Real)):
return Expression("MakeBoxes", expr, f)
p = dps(expr.get_precision()) if isinstance(expr, Real) else 0
try:
val = convert_base(expr.get_real_value(), base, p)
except ValueError:
return evaluation.message('BaseForm', 'basf', n)
if f.get_name() == 'System`OutputForm':
return from_python("%s_%d" % (val, base))
else:
return Expression(
'SubscriptBox', from_python(val), from_python(base))
示例2: construct_graphics
def construct_graphics(self, triangles, mesh_points, v_min, v_max, options, evaluation):
mesh_option = self.get_option(options, "Mesh", evaluation)
mesh = mesh_option.to_python()
graphics = []
for p1, p2, p3 in triangles:
graphics.append(
Expression(
"Polygon",
Expression("List", Expression("List", *p1), Expression("List", *p2), Expression("List", *p3)),
)
)
# Add the Grid
if mesh == "Full":
for xi in range(len(mesh_points)):
line = []
for yi in range(len(mesh_points[xi])):
line.append(
Expression("List", mesh_points[xi][yi][0], mesh_points[xi][yi][1], mesh_points[xi][yi][2])
)
graphics.append(Expression("Line", Expression("List", *line)))
elif mesh == "All":
for p1, p2, p3 in triangles:
line = [from_python(p1), from_python(p2), from_python(p3)]
graphics.append(Expression("Line", Expression("List", *line)))
return graphics
示例3: apply
def apply(self, interval, n, evaluation):
'RandomPrime[interval_?ListQ, n_]'
if not isinstance(n, Integer):
evaluation.message('RandomPrime', 'posdim', n)
return
py_n = n.to_python()
py_int = interval.to_python()
if not (isinstance(py_int, list) and len(py_int) == 2):
evaluation.message('RandomPrime', 'prmrng', interval)
imin, imax = min(py_int), max(py_int)
if imin <= 0 or not isinstance(imin, int):
evaluation.message('RandomPrime', 'posint', interval.leaves[0])
return
if imax <= 0 or not isinstance(imax, int):
evaluation.message('RandomPrime', 'posint', interval.leaves[1])
return
try:
if py_n == 1:
return from_python(sympy.ntheory.randprime(imin, imax + 1))
return from_python([sympy.ntheory.randprime(imin, imax + 1)
for i in range(py_n)])
except ValueError:
evaluation.message('RandomPrime', 'noprime')
return
示例4: apply_min
def apply_min(self, xmin, ymin, zmin, evaluation):
'Cuboid[{xmin_, ymin_, zmin_}]'
xmin, ymin, zmin = [value.round_to_float(evaluation)
for value in (xmin, ymin, zmin)]
if None in (xmin, ymin, zmin):
return # TODO
(xmax, ymax, zmax) = (from_python(value + 1)
for value in (xmin, ymin, zmin))
(xmin, ymin, zmin) = (from_python(value)
for value in (xmin, ymin, zmin))
return self.apply_full(xmin, ymin, zmin, xmax, ymax, zmax, evaluation)
示例5: apply_spec
def apply_spec(self, epochtime, evaluation):
'AbsoluteTime[epochtime_]'
datelist = self.to_datelist(epochtime, evaluation)
if datelist is None:
return
date = _Date(datelist=datelist)
tdelta = date.date - EPOCH_START
if tdelta.microseconds == 0:
return from_python(int(total_seconds(tdelta)))
return from_python(total_seconds(tdelta))
示例6: apply_min
def apply_min(self, xmin, ymin, zmin, evaluation):
'Cuboid[{xmin_, ymin_, zmin_}]'
try:
xmin, ymin, zmin = [value.to_number(
n_evaluation=evaluation) for value in (xmin, ymin, zmin)]
except NumberError:
# TODO
return
(xmax, ymax, zmax) = (from_python(value + 1)
for value in (xmin, ymin, zmin))
(xmin, ymin, zmin) = (from_python(value)
for value in (xmin, ymin, zmin))
return self.apply_full(xmin, ymin, zmin, xmax, ymax, zmax, evaluation)
示例7: fold
def fold(self, x, l):
# computes fold(x, l) with the internal _fold function. will start
# its evaluation machine precision, and will escalate to arbitrary
# precision if or symbolical evaluation only if necessary. folded
# items already computed are carried over to new evaluation modes.
yield x # initial state
init = None
operands = list(self._operands(x, l))
spans = self._spans(operands)
for mode in (self.FLOAT, self.MPMATH, self.SYMBOLIC):
s_operands = [y[1:] for y in operands[spans[mode]]]
if not s_operands:
continue
if mode == self.MPMATH:
from mathics.core.numbers import min_prec
precision = min_prec(*[t for t in chain(*s_operands) if t is not None])
working_precision = mpmath.workprec
else:
@contextmanager
def working_precision(_):
yield
precision = None
if mode == self.FLOAT:
def out(z):
return Real(z)
elif mode == self.MPMATH:
def out(z):
return Real(z, precision)
else:
def out(z):
return z
as_operand = self.operands.get(mode)
def converted_operands():
for y in s_operands:
yield tuple(as_operand(t) for t in y)
with working_precision(precision):
c_operands = converted_operands()
if init is not None:
c_init = tuple((None if t is None else as_operand(from_python(t))) for t in init)
else:
c_init = next(c_operands)
init = tuple((None if t is None else out(t)) for t in c_init)
generator = self._fold(
c_init, c_operands, self.math.get(mode))
for y in generator:
y = tuple(out(t) for t in y)
yield y
init = y
示例8: message
def message(self, symbol, tag, *args):
from mathics.core.expression import String, Symbol, Expression, from_python
# Allow evaluation.message('MyBuiltin', ...) (assume
# System`MyBuiltin)
symbol = ensure_context(symbol)
quiet_messages = set(self.get_quiet_messages())
pattern = Expression("MessageName", Symbol(symbol), String(tag))
if pattern in quiet_messages or self.quiet_all:
return
# Shorten the symbol's name according to the current context
# settings. This makes sure we print the context, if it would
# be necessary to find the symbol that this message is
# attached to.
symbol_shortname = self.definitions.shorten_name(symbol)
if settings.DEBUG_PRINT:
print("MESSAGE: %s::%s (%s)" % (symbol_shortname, tag, args))
text = self.definitions.get_value(symbol, "System`Messages", pattern, self)
if text is None:
pattern = Expression("MessageName", Symbol("General"), String(tag))
text = self.definitions.get_value("System`General", "System`Messages", pattern, self)
if text is None:
text = String("Message %s::%s not found." % (symbol_shortname, tag))
text = self.format_output(Expression("StringForm", text, *(from_python(arg) for arg in args)), "text")
self.out.append(Message(symbol_shortname, tag, text))
self.output.out(self.out[-1])
示例9: compute
def compute(user_hash, py_hashtype):
hash_func = Hash._supported_hashes.get(py_hashtype)
if hash_func is None: # unknown hash function?
return # in order to return original Expression
h = hash_func()
user_hash(h.update)
return from_python(int(h.hexdigest(), 16))
示例10: apply
def apply(self, f, expr, n, evaluation):
'FixedPointList[f_, expr_, n_:DirectedInfinity[1]]'
if n == Expression('DirectedInfinity', 1):
count = None
else:
count = n.get_int_value()
if count is None or count < 0:
evaluation.message('FixedPoint', 'intnn')
return
interm = expr
result = [interm]
index = 0
while count is None or index < count:
evaluation.check_stopped()
new_result = Expression(f, interm).evaluate(evaluation)
result.append(new_result)
if new_result == interm:
break
interm = new_result
index += 1
return from_python(result)
示例11: pyobject
def pyobject(self, ex, obj):
from mathics.core import expression
from mathics.core.expression import Number
if obj is None:
return expression.Symbol('Null')
elif isinstance(obj, (list, tuple)) or is_Vector(obj):
return expression.Expression('List', *(from_sage(item, self.subs) for item in obj))
elif isinstance(obj, Constant):
return expression.Symbol(obj._conversions.get('mathematica', obj._name))
elif is_Integer(obj):
return expression.Integer(str(obj))
elif isinstance(obj, sage.Rational):
rational = expression.Rational(str(obj))
if rational.value.denom() == 1:
return expression.Integer(rational.value.numer())
else:
return rational
elif isinstance(obj, sage.RealDoubleElement) or is_RealNumber(obj):
return expression.Real(str(obj))
elif is_ComplexNumber(obj):
real = Number.from_string(str(obj.real())).value
imag = Number.from_string(str(obj.imag())).value
return expression.Complex(real, imag)
elif isinstance(obj, NumberFieldElement_quadratic):
# TODO: this need not be a complex number, but we assume so!
real = Number.from_string(str(obj.real())).value
imag = Number.from_string(str(obj.imag())).value
return expression.Complex(real, imag)
else:
return expression.from_python(obj)
示例12: apply
def apply(self, string, patt, evaluation, options):
'StringSplit[string_, patt_, OptionsPattern[%(name)s]]'
py_string = string.get_string_value()
if py_string is None:
return evaluation.message('StringSplit', 'strse', Integer(1),
Expression('StringSplit', string))
if patt.has_form('List', None):
patts = patt.get_leaves()
else:
patts = [patt]
re_patts = []
for p in patts:
py_p = to_regex(p)
if py_p is None:
return evaluation.message('StringExpression', 'invld', p, patt)
re_patts.append(py_p)
flags = re.MULTILINE
if options['System`IgnoreCase'] == Symbol('True'):
flags = flags | re.IGNORECASE
result = [py_string]
for re_patt in re_patts:
result = [t for s in result for t in mathics_split(re_patt, s, flags=flags)]
return from_python([x for x in result if x != ''])
示例13: message
def message(self, symbol, tag, *args):
from mathics.core.expression import (String, Symbol, Expression,
from_python)
if (symbol, tag) in self.quiet_messages or self.quiet_all:
return
if settings.DEBUG_PRINT:
print 'MESSAGE: %s::%s (%s)' % (symbol, tag, args)
pattern = Expression('MessageName', Symbol(symbol), String(tag))
text = self.definitions.get_value(symbol, 'Messages', pattern, self)
if text is None:
pattern = Expression('MessageName', Symbol('General'), String(tag))
text = self.definitions.get_value(
'General', 'Messages', pattern, self)
if text is None:
text = String("Message %s::%s not found." % (symbol, tag))
text = self.format_output(Expression(
'StringForm', text, *(from_python(arg) for arg in args)))
self.out.append(Message(symbol, tag, text))
if self.out_callback:
self.out_callback(self.out[-1])
示例14: apply
def apply(self, filename, evaluation):
'Import[filename_]'
result = self.importer(filename, evaluation)
if result is None:
return Symbol('$Failed')
return from_python(result['Data'])
示例15: _add_continuous_widget
def _add_continuous_widget(self, symbol, label, default, minimum, maximum, evaluation):
minimum_value = minimum.to_python()
maximum_value = maximum.to_python()
if minimum_value > maximum_value:
raise IllegalWidgetArguments(symbol)
else:
defval = min(max(default.to_python(), minimum_value), maximum_value)
widget = _create_widget(FloatSlider, value=defval, min=minimum_value, max=maximum_value)
self._add_widget(widget, symbol.get_name(), lambda x: from_python(x), label)