本文整理汇总了Python中pymbolic.var函数的典型用法代码示例。如果您正苦于以下问题:Python var函数的具体用法?Python var怎么用?Python var使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了var函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: map_subscript
def map_subscript(self, expr, type_context):
from loopy.kernel.data import TemporaryVariable
ary = self.find_array(expr)
if (isinstance(ary, TemporaryVariable)
and ary.address_space == AddressSpace.PRIVATE):
# generate access code for acccess to private-index temporaries
gsize, lsize = self.kernel.get_grid_size_upper_bounds_as_exprs()
if lsize:
lsize, = lsize
from loopy.kernel.array import get_access_info
from pymbolic import evaluate
access_info = get_access_info(self.kernel.target, ary, expr.index,
lambda expr: evaluate(expr, self.codegen_state.var_subst_map),
self.codegen_state.vectorization_info)
subscript, = access_info.subscripts
result = var(access_info.array_name)[
var("programIndex") + self.rec(lsize*subscript, 'i')]
if access_info.vector_index is not None:
return self.kernel.target.add_vector_access(
result, access_info.vector_index)
else:
return result
return super(ExprToISPCExprMapper, self).map_subscript(
expr, type_context)
示例2: map_Assignment
def map_Assignment(self, node):
lhs = self.parse_expr(node.variable)
from pymbolic.primitives import Subscript
if isinstance(lhs, Subscript):
lhs_name = lhs.aggregate.name
else:
lhs_name = lhs.name
scope = self.scope_stack[-1]
scope.use_name(lhs_name)
infer_type = scope.get_type_inference_mapper()
rhs = self.parse_expr(node.expr)
lhs_dtype = infer_type(lhs)
rhs_dtype = infer_type(rhs)
# check for silent truncation of complex
if lhs_dtype.kind != 'c' and rhs_dtype.kind == 'c':
from pymbolic import var
rhs = var("real")(rhs)
# check for silent widening of real
if lhs_dtype.kind == 'c' and rhs_dtype.kind != 'c':
from pymbolic import var
rhs = var("fromreal")(rhs)
return cgen.Assign(self.gen_expr(lhs), self.gen_expr(rhs))
示例3: get_kernel
def get_kernel():
from sumpy.symbolic import pymbolic_real_norm_2
from pymbolic.primitives import make_sym_vector
from pymbolic import var
d = make_sym_vector("d", 3)
r = pymbolic_real_norm_2(d[:-1])
# r3d = pymbolic_real_norm_2(d)
#expr = var("log")(r3d)
log = var("log")
sqrt = var("sqrt")
a = d[-1]
expr = log(r)
expr = log(sqrt(r**2 + a**2))
expr = log(sqrt(r + a**2))
#expr = log(sqrt(r**2 + a**2))-a**2/2/(r**2+a**2)
#expr = 2*log(sqrt(r**2 + a**2))
scaling = 1/(2*var("pi"))
from sumpy.kernel import ExpressionKernel
return ExpressionKernel(
dim=3,
expression=expr,
global_scaling_const=scaling,
is_complex_valued=False)
示例4: map_reduction
def map_reduction(expr, rec, nresults=1):
if frozenset(expr.inames) != inames_set:
return type(expr)(
operation=expr.operation,
inames=expr.inames,
expr=rec(expr.expr),
allow_simultaneous=expr.allow_simultaneous)
if subst_rule_name is None:
subst_rule_prefix = "red_%s_arg" % "_".join(inames)
my_subst_rule_name = var_name_gen(subst_rule_prefix)
else:
my_subst_rule_name = subst_rule_name
if my_subst_rule_name in substs:
raise LoopyError("substitution rule '%s' already exists"
% my_subst_rule_name)
from loopy.kernel.data import SubstitutionRule
substs[my_subst_rule_name] = SubstitutionRule(
name=my_subst_rule_name,
arguments=tuple(inames),
expression=expr.expr)
from pymbolic import var
iname_vars = [var(iname) for iname in inames]
return type(expr)(
operation=expr.operation,
inames=expr.inames,
expr=var(my_subst_rule_name)(*iname_vars),
allow_simultaneous=expr.allow_simultaneous)
示例5: map_planned_flux
def map_planned_flux(self, expr):
try:
return self.expr_to_var[expr]
except KeyError:
for fb in self.flux_batches:
try:
idx = fb.flux_exprs.index(expr)
except ValueError:
pass
else:
# found at idx
mapped_fluxes = [
self.internal_map_flux(f)
for f in fb.flux_exprs]
names = [self.get_var_name() for f in mapped_fluxes]
self.code.append(
self.make_flux_batch_assign(
names, mapped_fluxes, fb.repr_op))
from pymbolic import var
for n, f in zip(names, fb.flux_exprs):
self.expr_to_var[f] = var(n)
return var(names[idx])
raise RuntimeError("flux '%s' not in any flux batch" % expr)
示例6: map_substitution
def map_substitution(self, name, tag, arguments, expn_state):
if not (
name == self.subst_name
and self.within(
expn_state.kernel,
expn_state.instruction,
expn_state.stack)
and (self.subst_tag is None or self.subst_tag == tag)):
return super(RuleInvocationReplacer, self).map_substitution(
name, tag, arguments, expn_state)
# {{{ check if in footprint
rule = self.rule_mapping_context.old_subst_rules[name]
arg_context = self.make_new_arg_context(
name, rule.arguments, arguments, expn_state.arg_context)
args = [arg_context[arg_name] for arg_name in rule.arguments]
accdesc = AccessDescriptor(
storage_axis_exprs=storage_axis_exprs(
self.storage_axis_sources, args))
if not self.array_base_map.is_access_descriptor_in_footprint(accdesc):
return super(RuleInvocationReplacer, self).map_substitution(
name, tag, arguments, expn_state)
# }}}
assert len(arguments) == len(rule.arguments)
abm = self.array_base_map
stor_subscript = []
for sax_name, sax_source, sax_base_idx in zip(
self.storage_axis_names,
self.storage_axis_sources,
abm.storage_base_indices):
if sax_name not in self.non1_storage_axis_names:
continue
if isinstance(sax_source, int):
# an argument
ax_index = arguments[sax_source]
else:
# an iname
ax_index = var(sax_source)
from loopy.isl_helpers import simplify_via_aff
ax_index = simplify_via_aff(ax_index - sax_base_idx)
stor_subscript.append(ax_index)
new_outer_expr = var(self.temporary_name)
if stor_subscript:
new_outer_expr = new_outer_expr.index(tuple(stor_subscript))
# Can't possibly be nested, and no need to traverse
# further as compute expression has already been seen
# by rule_mapping_context.
return new_outer_expr
示例7: transform_access
def transform_access(self, index, expn_state):
my_insn_id = expn_state.insn_id
if my_insn_id in self.definition_insn_ids:
return None
my_def_id = self.usage_to_definition[my_insn_id]
if not self.within(
expn_state.kernel,
expn_state.instruction,
expn_state.stack):
self.saw_unmatched_usage_sites[my_def_id] = True
return None
subst_name = self.get_subst_name(my_def_id)
if self.extra_arguments:
if index is None:
index = self.extra_arguments
else:
index = index + self.extra_arguments
from pymbolic import var
if index is None:
return var(subst_name)
elif not isinstance(index, tuple):
return var(subst_name)(index)
else:
return var(subst_name)(*index)
示例8: get_kernel_exprs
def get_kernel_exprs(self, result_names):
isrc_sym = var("isrc")
exprs = [var(name) * self.get_strength_or_not(isrc_sym, i)
for i, name in enumerate(result_names)]
return [lp.Assignment(id=None,
assignee="pair_result_%d" % i, expression=expr,
temp_var_type=lp.auto)
for i, expr in enumerate(exprs)]
示例9: test_child_invalid_type_cast
def test_child_invalid_type_cast():
from pymbolic import var
knl = lp.make_kernel(
"{[i]: 0<=i<n}",
["<> ctr = make_uint2(0, 0)",
lp.Assignment("a[i]", lp.TypeCast(np.int64, var("ctr")) << var("i"))]
)
with pytest.raises(lp.LoopyError):
knl = lp.preprocess_kernel(knl)
示例10: test_is_expression_equal
def test_is_expression_equal():
from loopy.symbolic import is_expression_equal
from pymbolic import var
x = var("x")
y = var("y")
assert is_expression_equal(x+2, 2+x)
assert is_expression_equal((x+2)**2, x**2 + 4*x + 4)
assert is_expression_equal((x+y)**2, x**2 + 2*x*y + y**2)
示例11: apply_offset
def apply_offset(sub):
import loopy as lp
if ary.offset:
if ary.offset is lp.auto:
return var(array_name+"_offset") + sub
elif isinstance(ary.offset, str):
return var(ary.offset) + sub
else:
# assume it's an expression
return ary.offset + sub
else:
return sub
示例12: map_field_component
def map_field_component(self, expr):
if expr.is_interior:
where = "int_side"
else:
where = "ext_side"
arg_name = self.flux_var_info.flux_idx_and_dep_to_arg_name[
self.flux_idx, expr]
if not arg_name:
return 0
else:
from pymbolic import var
return var(arg_name+"_it")[var(where+"_idx")]
示例13: get_kernel_exprs
def get_kernel_exprs(self, result_names):
from pymbolic import var
isrc_sym = var("isrc")
exprs = [var(name) * self.get_strength_or_not(isrc_sym, i)
for i, name in enumerate(result_names)]
if self.exclude_self:
from pymbolic.primitives import If, Variable
exprs = [If(Variable("is_self"), 0, expr) for expr in exprs]
return [lp.Assignment(id=None,
assignee="pair_result_%d" % i, expression=expr,
temp_var_type=lp.auto)
for i, expr in enumerate(exprs)]
示例14: handle_alloc
def handle_alloc(self, gen, arg, kernel_arg, strify, skip_arg_checks):
"""
Handle allocation of non-specified arguements for pyopencl execution
"""
from pymbolic import var
num_axes = len(arg.strides)
for i in range(num_axes):
gen("_lpy_shape_%d = %s" % (i, strify(arg.unvec_shape[i])))
itemsize = kernel_arg.dtype.numpy_dtype.itemsize
for i in range(num_axes):
gen("_lpy_strides_%d = %s" % (i, strify(
itemsize*arg.unvec_strides[i])))
if not skip_arg_checks:
for i in range(num_axes):
gen("assert _lpy_strides_%d > 0, "
"\"'%s' has negative stride in axis %d\""
% (i, arg.name, i))
sym_strides = tuple(
var("_lpy_strides_%d" % i)
for i in range(num_axes))
sym_shape = tuple(
var("_lpy_shape_%d" % i)
for i in range(num_axes))
alloc_size_expr = (sum(astrd*(alen-1)
for alen, astrd in zip(sym_shape, sym_strides))
+ itemsize)
gen("_lpy_alloc_size = %s" % strify(alloc_size_expr))
gen("%(name)s = _lpy_cl_array.Array(queue, %(shape)s, "
"%(dtype)s, strides=%(strides)s, "
"data=allocator(_lpy_alloc_size), allocator=allocator)"
% dict(
name=arg.name,
shape=strify(sym_shape),
strides=strify(sym_strides),
dtype=self.python_dtype_str(kernel_arg.dtype.numpy_dtype)))
if not skip_arg_checks:
for i in range(num_axes):
gen("del _lpy_shape_%d" % i)
gen("del _lpy_strides_%d" % i)
gen("del _lpy_alloc_size")
gen("")
示例15: test_tim2d
def test_tim2d(ctx_factory):
dtype = np.float32
ctx = ctx_factory()
order = "C"
n = 8
from pymbolic import var
K_sym = var("K")
field_shape = (K_sym, n, n)
# K - run-time symbolic
knl = lp.make_kernel(ctx.devices[0],
"[K] -> {[i,j,e,m,o,gi]: 0<=i,j,m,o<%d and 0<=e<K and 0<=gi<3}" % n,
[
"ur(a,b) := sum_float32(@o, D[a,o]*u[e,o,b])",
"us(a,b) := sum_float32(@o, D[b,o]*u[e,a,o])",
"lap[e,i,j] = "
" sum_float32(m, D[m,i]*(G[0,e,m,j]*ur(m,j) + G[1,e,m,j]*us(m,j)))"
"+ sum_float32(m, D[m,j]*(G[1,e,i,m]*ur(i,m) + G[2,e,i,m]*us(i,m)))"
],
[
lp.ArrayArg("u", dtype, shape=field_shape, order=order),
lp.ArrayArg("lap", dtype, shape=field_shape, order=order),
lp.ArrayArg("G", dtype, shape=(3,)+field_shape, order=order),
# lp.ConstantArrayArg("D", dtype, shape=(n, n), order=order),
lp.ArrayArg("D", dtype, shape=(n, n), order=order),
# lp.ImageArg("D", dtype, shape=(n, n)),
lp.ValueArg("K", np.int32, approximately=1000),
],
name="semlap2D", assumptions="K>=1")
unroll = 32
seq_knl = knl
knl = lp.add_prefetch(knl, "D", ["m", "j", "i","o"], default_tag="l.auto")
knl = lp.add_prefetch(knl, "u", ["i", "j", "o"], default_tag="l.auto")
knl = lp.precompute(knl, "ur", np.float32, ["a", "b"], default_tag="l.auto")
knl = lp.precompute(knl, "us", np.float32, ["a", "b"], default_tag="l.auto")
knl = lp.split_iname(knl, "e", 1, outer_tag="g.0")#, slabs=(0, 1))
knl = lp.tag_inames(knl, dict(i="l.0", j="l.1"))
knl = lp.tag_inames(knl, dict(o="unr"))
knl = lp.tag_inames(knl, dict(m="unr"))
# knl = lp.add_prefetch(knl, "G", [2,3], default_tag=None) # axis/argument indices on G
knl = lp.add_prefetch(knl, "G", [2,3], default_tag="l.auto") # axis/argument indices on G
kernel_gen = lp.generate_loop_schedules(knl)
kernel_gen = lp.check_kernels(kernel_gen, dict(K=1000))
K = 1000
lp.auto_test_vs_ref(seq_knl, ctx, kernel_gen,
op_count=K*(n*n*n*2*2 + n*n*2*3 + n**3 * 2*2)/1e9,
op_label="GFlops",
parameters={"K": K})