本文整理汇总了Python中sympy.parsing.sympy_parser.parse_expr方法的典型用法代码示例。如果您正苦于以下问题:Python sympy_parser.parse_expr方法的具体用法?Python sympy_parser.parse_expr怎么用?Python sympy_parser.parse_expr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy.parsing.sympy_parser
的用法示例。
在下文中一共展示了sympy_parser.parse_expr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_unyt_expr
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def parse_unyt_expr(unit_expr):
if not unit_expr:
# Bug catch...
# if unit_expr is an empty string, parse_expr fails hard...
unit_expr = "1"
# Avoid a parse error if someone uses the percent unit and the
# parser tries to interpret it as the modulo operator
unit_expr = unit_expr.replace("%", "percent")
unit_expr = unit_expr.replace("°", "deg")
try:
unit_expr = parse_expr(
unit_expr, global_dict=global_dict, transformations=unit_text_transform
)
except Exception as e:
msg = "Unit expression '%s' raised an error during parsing:\n%s" % (
unit_expr,
repr(e),
)
raise UnitParseError(msg)
return unit_expr
示例2: convert_to_function
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def convert_to_function(string: str, scale_by_k=False):
"""Using the sympy module, parse string input
into a mathematical expression.
Returns the original string, the latexified string,
the mathematical expression in terms of sympy symbols,
and a lambdified function
"""
string = string.replace("^", "**")
symbolic_function = parse_expr(string)
if scale_by_k:
latexstring = latex(symbolic_function*abc.k)
else:
latexstring = latex(symbolic_function)
lambda_function = lambdify(abc.x, symbolic_function,
modules=module_list)
string = string.replace('*', '')
latexstring = "$" + latexstring + "$"
return string, latexstring, \
symbolic_function, lambda_function
示例3: string_to_sympy
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def string_to_sympy(s):
"""Convert any string to a sympy object or None."""
if isinstance(s, int):
return sympy.Integer(s)
elif isinstance(s, list):
return tuple([string_to_sympy(e) for e in s])
elif s is None:
return None
else:
# Step 1 build expression with the whole alphabet redefined:
local_dict = {c: symbol_pos_int(c) for c in s if c in string.ascii_letters}
# TODO find nicer solution for N and other pre-mapped letters
preliminary_expr = parse_expr(s, local_dict=local_dict)
# Replace all free symbols with positive integer versions:
local_dict.update(
{s.name: symbol_pos_int(s.name) for s in preliminary_expr.free_symbols})
return parse_expr(s, local_dict=local_dict)
示例4: parse_perfmetric
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def parse_perfmetric(metric):
"""Return (sympy expressions, event names and symbols dict) from performance metric str."""
# Find all perfs counter references
perfcounters = re.findall(r'[A-Z0-9_]+:[A-Z0-9\[\]|\-]+(?::[A-Za-z0-9\-_=]+)*', metric)
# Build a temporary metric, with parser-friendly Symbol names
temp_metric = metric
temp_pc_names = {"SYM{}".format(re.sub("[\[\]\-|=:]", "_", pc)): pc
for i, pc in enumerate(perfcounters)}
for var_name, pc in temp_pc_names.items():
temp_metric = temp_metric.replace(pc, var_name)
# Parse temporary expression
expr = parse_expr(temp_metric)
# Rename symbols to originals
for s in expr.free_symbols:
if s.name in temp_pc_names:
s.name = temp_pc_names[str(s)]
events = {s: MachineModel.parse_perfctr_event(s.name) for s in expr.free_symbols
if s.name in perfcounters}
return expr, events
示例5: test_parse
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def test_parse(self):
from sympy.parsing.sympy_parser import parse_expr
assert parse_expr('x^2') == ts.parse_expression('x^2')
示例6: parse_expression
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def parse_expression(expr):
'''Parse string as sympy expression
Args:
expr (string): string to convert to sympy expression
'''
return parse_expr(expr, transformations=(_st + (_ima,)))
示例7: __init__
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def __init__(self,
expression: str,
optimization: bool = False,
mct_mode: str = 'basic') -> None:
"""
Args:
expression: The string of the desired logical expression.
It could be either in the DIMACS CNF format,
or a general boolean logical expression, such as 'a ^ b' and 'v[0] & (~v[1] | v[2])'
optimization: Boolean flag for attempting logical expression optimization
mct_mode: The mode to use for building Multiple-Control Toffoli.
Raises:
AquaError: Invalid input
"""
validate_in_set('mct_mode', mct_mode,
{'basic', 'basic-dirty-ancilla',
'advanced', 'noancilla'})
super().__init__()
self._mct_mode = mct_mode.strip().lower()
self._optimization = optimization
expression = re.sub('(?i)' + re.escape(' and '), ' & ', expression)
expression = re.sub('(?i)' + re.escape(' xor '), ' ^ ', expression)
expression = re.sub('(?i)' + re.escape(' or '), ' | ', expression)
expression = re.sub('(?i)' + re.escape('not '), '~', expression)
orig_expression = expression
# try parsing as normal logical expression that sympy recognizes
try:
raw_expr = parse_expr(expression)
except Exception: # pylint: disable=broad-except
# try parsing as dimacs cnf
try:
expression = LogicalExpressionOracle._dimacs_cnf_to_expression(expression)
raw_expr = parse_expr(expression)
except Exception:
raise AquaError('Failed to parse the input expression: {}.'.format(orig_expression))
self._expr = raw_expr
self._process_expr()
self.construct_circuit()
示例8: __init__
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def __init__(self, function_name: str,
param: Union[basic.Basic, str]) -> None:
"""
The initializer. The parameter must be a
string representation of a function, and it needs to
be at least a function of x.
"""
# Dictionary of modules and user defined functions.
# Used for lambdify from sympy to parse input.
if isinstance(param, str):
param = parse_expr(param)
if function_name == "x":
function_name = "1.0*x"
self._symbolic_func = parse_expr(function_name)
symbol_set = self._symbolic_func.free_symbols
if abc.k in symbol_set:
k_param = parse_expr("k_param")
self._symbolic_func = self._symbolic_func.subs(abc.k, k_param)
symbol_set = self._symbolic_func.free_symbols
symbol_list = list(symbol_set)
if param not in symbol_list:
raise VariableNotFoundError
self.latex_repr = latex(self._symbolic_func)
symbol_list.remove(param)
self.parameters = symbol_list
var_list = [param]
var_list.extend(symbol_list)
self.symbols = var_list
self._lambda_func = lambdify(
self.symbols, self._symbolic_func, modules=self.module_list)
示例9: multiply_latex_string
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def multiply_latex_string(self, var: str) -> str:
var = parse_expr(var)
expr = var*self._symbolic_func
return latex(expr)
示例10: simplify_arith_expr
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def simplify_arith_expr(expr):
try:
out = repr(sympy_parser.parse_expr(str(expr)))
return out
except:
print "Couldn't parse", expr
raise
示例11: _evaluate_variable_expression
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def _evaluate_variable_expression(self, expr, units):
"""
:type expr: str
:type units: str
:return: float
"""
try:
sexp = sympy_parser.parse_expr(expr)
except SyntaxError:
return Q(expr).to(units).magnitude
sub_exprs = {fs: self.get_variable_value(fs.name) for fs in sexp.free_symbols}
return float(sexp.subs({fs: self._evaluate_variable_expression(e, units) for fs, e in sub_exprs.items()}))
示例12: sanitize_symbolname
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def sanitize_symbolname(name):
"""
Sanitize all characters not matched to a symbol by sympy's parse_expr.
Based on same rules as used for python variables.
"""
return re.subn('(^[0-9])|[^0-9a-zA-Z_]', '_', name)[0]
示例13: convert_to_dict
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def convert_to_dict(node: Node) -> dict:
children = OrderedDict()
for node_property in node.properties:
children[node_property] = convert_to_dict(node[node_property][0])
simplified = str(sympy.expand(parse_expr(''.join(to_token_sequence(node, [])))))
if len(children) > 0:
return dict(Name=node.name, Children=children, Symbol=simplified)
else:
return dict(Name=node.name, Symbol=simplified)
示例14: convert_to_dict
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def convert_to_dict(node: Node) -> dict:
children = OrderedDict()
for node_property in node.properties:
children[node_property] = convert_to_dict(node[node_property][0])
simplified = str(simplify_logic(parse_expr(''.join(to_token_sequence(node, []))), form='dnf'))
if len(children) > 0:
return dict(Name=node.name, Children=children, Symbol=simplified)
else:
return dict(Name=node.name, Symbol=simplified)
示例15: add_equation
# 需要导入模块: from sympy.parsing import sympy_parser [as 别名]
# 或者: from sympy.parsing.sympy_parser import parse_expr [as 别名]
def add_equation(self, eqn_str, eqn_name='', subs_dict=None):
"""Add an equation to the physics layer.
The equation string should represent the expression for computing the residue of a given
equation, rather than representing the equation itself. Use dif(y,x) for computing the
derivate of y with respect to x. Sign of the expression does not matter. The variable names
**MUST** be the same as the variables in self.in_vars and self.out_vars.
E.g.,
For the equation partial(u, x) + partial(v, y) = 3*partial(u, y)*partial(v, x), write as:
eqn_str = 'dif(u,x)+dif(v,y)-3*dif(u,y)*dif(v,x)'
- or -
eqn_str = '3*dif(u,y)*dif(v,x)-(dif(u,x)+dif(v,y))'
Args:
eqn_str: str, a string that can be parsed as an experession for computing the residue of
an equation.
eqn_name: str, a name or identifier for this equation entry. E.g., 'div_free'. If none or
empty, use default of eqn_i where i is an index.
subs_dict: dict, a dictionary where the key (str) is the variable to subsitute and val
(str) is the expression to substitite the variable with. useful for scenarios such as
normalizations and/or non-dimensionalizing expressions.
Raises:
ValueError: when the variables in the eqn_str do not match that of in_vars and out_vars.
"""
if not eqn_name:
eqn_name = 'eqn_{i}'.format(len(self.eqns_raw.keys()))
# assert that the equation contains the same vars as in_vars and out_vars
expr = parse_expr(eqn_str)
# substitute variables in the equation.
if subs_dict:
for key, val in subs_dict.items():
expr = expr.subs(key, val)
valid_var = expr.free_symbols <= (set(self.in_vars)|set(self.out_vars))
if not valid_var:
raise ValueError('Variables in the eqn_str ({}) does not match that of '
'in_vars ({}) and out_vars ({})'.format(expr.free_symbols,
set(self.in_vars),
set(self.out_vars)))
# convert into lambda functions
fn = sympy.lambdify(self.all_vars, expr, {'dif': torch_diff})
# update equations
self.eqns_raw.update({eqn_name: eqn_str})
self.eqns_fn.update({eqn_name: fn})