本文整理汇总了Python中numba.cgutils.ifelse函数的典型用法代码示例。如果您正苦于以下问题:Python ifelse函数的具体用法?Python ifelse怎么用?Python ifelse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ifelse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: timedelta_sign_impl
def timedelta_sign_impl(context, builder, sig, args):
val, = args
ret = alloc_timedelta_result(builder)
zero = Constant.int(TIMEDELTA64, 0)
with cgutils.ifelse(builder, builder.icmp(lc.ICMP_SGT, val, zero)
) as (gt_zero, le_zero):
with gt_zero:
builder.store(Constant.int(TIMEDELTA64, 1), ret)
with le_zero:
with cgutils.ifelse(builder, builder.icmp(lc.ICMP_EQ, val, zero)
) as (eq_zero, lt_zero):
with eq_zero:
builder.store(Constant.int(TIMEDELTA64, 0), ret)
with lt_zero:
builder.store(Constant.int(TIMEDELTA64, -1), ret)
return builder.load(ret)
示例2: getiter_range_generic
def getiter_range_generic(context, builder, iterobj, start, stop, step):
diff = builder.sub(stop, start)
intty = start.type
zero = Constant.int(intty, 0)
one = Constant.int(intty, 1)
pos_diff = builder.icmp(lc.ICMP_SGT, diff, zero)
pos_step = builder.icmp(lc.ICMP_SGT, step, zero)
sign_differs = builder.xor(pos_diff, pos_step)
zero_step = builder.icmp(lc.ICMP_EQ, step, zero)
with cgutils.if_unlikely(builder, zero_step):
# step shouldn't be zero
context.return_errcode(builder, 1)
with cgutils.ifelse(builder, sign_differs) as (then, orelse):
with then:
builder.store(zero, iterobj.count)
with orelse:
rem = builder.srem(diff, step)
uneven = builder.icmp(lc.ICMP_SGT, rem, zero)
newcount = builder.add(builder.sdiv(diff, step),
builder.select(uneven, one, zero))
builder.store(newcount, iterobj.count)
return iterobj._getvalue()
示例3: to_native_optional
def to_native_optional(self, obj, typ):
"""
Convert object *obj* to a native optional structure.
"""
noneval = self.context.make_optional_none(self.builder, typ.type)
is_not_none = self.builder.icmp(lc.ICMP_NE, obj, self.borrow_none())
retptr = cgutils.alloca_once(self.builder, noneval.type)
errptr = cgutils.alloca_once_value(self.builder, cgutils.false_bit)
with cgutils.ifelse(self.builder, is_not_none) as (then, orelse):
with then:
native = self.to_native_value(obj, typ.type)
just = self.context.make_optional_value(self.builder,
typ.type, native.value)
self.builder.store(just, retptr)
self.builder.store(native.is_error, errptr)
with orelse:
self.builder.store(ir.Constant(noneval.type, ir.Undefined),
retptr)
self.builder.store(noneval, retptr)
if native.cleanup is not None:
def cleanup():
with cgutils.ifthen(self.builder, is_not_none):
native.cleanup()
else:
cleanup = None
ret = self.builder.load(retptr)
return NativeValue(ret, is_error=self.builder.load(errptr),
cleanup=cleanup)
示例4: _gauss_impl
def _gauss_impl(context, builder, sig, args, state):
# The type for all computations (either float or double)
ty = sig.return_type
llty = context.get_data_type(ty)
state_ptr = get_state_ptr(context, builder, state)
_random = {"py": random.random,
"np": np.random.random}[state]
ret = cgutils.alloca_once(builder, llty, name="result")
gauss_ptr = get_gauss_ptr(builder, state_ptr)
has_gauss_ptr = get_has_gauss_ptr(builder, state_ptr)
has_gauss = cgutils.is_true(builder, builder.load(has_gauss_ptr))
with cgutils.ifelse(builder, has_gauss) as (then, otherwise):
with then:
# if has_gauss: return it
builder.store(builder.load(gauss_ptr), ret)
builder.store(const_int(0), has_gauss_ptr)
with otherwise:
# if not has_gauss: compute a pair of numbers using the Box-Muller
# transform; keep one and return the other
pair = context.compile_internal(builder,
_gauss_pair_impl(_random),
signature(types.UniTuple(ty, 2)),
())
first, second = cgutils.unpack_tuple(builder, pair, 2)
builder.store(first, gauss_ptr)
builder.store(second, ret)
builder.store(const_int(1), has_gauss_ptr)
mu, sigma = args
return builder.fadd(mu,
builder.fmul(sigma, builder.load(ret)))
示例5: get_next_int
def get_next_int(context, builder, state_ptr, nbits):
"""
Get the next integer with width *nbits*.
"""
c32 = ir.Constant(nbits.type, 32)
def get_shifted_int(nbits):
shift = builder.sub(c32, nbits)
y = get_next_int32(context, builder, state_ptr)
return builder.lshr(y, builder.zext(shift, y.type))
ret = cgutils.alloca_once_value(builder, ir.Constant(int64_t, 0))
is_32b = builder.icmp_unsigned('<=', nbits, c32)
with cgutils.ifelse(builder, is_32b) as (ifsmall, iflarge):
with ifsmall:
low = get_shifted_int(nbits)
builder.store(builder.zext(low, int64_t), ret)
with iflarge:
# XXX This assumes nbits <= 64
low = get_next_int32(context, builder, state_ptr)
high = get_shifted_int(builder.sub(nbits, c32))
total = builder.add(
builder.zext(low, int64_t),
builder.shl(builder.zext(high, int64_t), ir.Constant(int64_t, 32)))
builder.store(total, ret)
return builder.load(ret)
示例6: _long_from_native_int
def _long_from_native_int(self, ival, func_name, native_int_type,
signed):
fnty = Type.function(self.pyobj, [native_int_type])
fn = self._get_function(fnty, name=func_name)
resptr = cgutils.alloca_once(self.builder, self.pyobj)
if PYVERSION < (3, 0):
# Under Python 2, we try to return a PyInt object whenever
# the given number fits in a C long.
pyint_fnty = Type.function(self.pyobj, [self.long])
pyint_fn = self._get_function(pyint_fnty, name="PyInt_FromLong")
long_max = Constant.int(native_int_type, _helperlib.long_max)
if signed:
long_min = Constant.int(native_int_type, _helperlib.long_min)
use_pyint = self.builder.and_(
self.builder.icmp(lc.ICMP_SGE, ival, long_min),
self.builder.icmp(lc.ICMP_SLE, ival, long_max),
)
else:
use_pyint = self.builder.icmp(lc.ICMP_ULE, ival, long_max)
with cgutils.ifelse(self.builder, use_pyint) as (then, otherwise):
with then:
downcast_ival = self.builder.trunc(ival, self.long)
res = self.builder.call(pyint_fn, [downcast_ival])
self.builder.store(res, resptr)
with otherwise:
res = self.builder.call(fn, [ival])
self.builder.store(res, resptr)
else:
fn = self._get_function(fnty, name=func_name)
self.builder.store(self.builder.call(fn, [ival]), resptr)
return self.builder.load(resptr)
示例7: complex128_power_impl
def complex128_power_impl(context, builder, sig, args):
[ca, cb] = args
a = Complex128(context, builder, value=ca)
b = Complex128(context, builder, value=cb)
c = Complex128(context, builder)
module = cgutils.get_module(builder)
pa = a._getpointer()
pb = b._getpointer()
pc = c._getpointer()
# Optimize for square because cpow looses a lot of precsiion
TWO = context.get_constant(types.float64, 2)
ZERO = context.get_constant(types.float64, 0)
b_real_is_two = builder.fcmp(lc.FCMP_OEQ, b.real, TWO)
b_imag_is_zero = builder.fcmp(lc.FCMP_OEQ, b.imag, ZERO)
b_is_two = builder.and_(b_real_is_two, b_imag_is_zero)
with cgutils.ifelse(builder, b_is_two) as (then, otherwise):
with then:
# Lower as multiplication
res = complex_mul_impl(context, builder, sig, (ca, ca))
cres = Complex128(context, builder, value=res)
c.real = cres.real
c.imag = cres.imag
with otherwise:
# Lower with call to external function
fnty = Type.function(Type.void(), [pa.type] * 3)
cpow = module.get_or_insert_function(fnty, name="numba.math.cpow")
builder.call(cpow, (pa, pb, pc))
return builder.load(pc)
示例8: timedelta_abs_impl
def timedelta_abs_impl(context, builder, sig, args):
val, = args
ret = alloc_timedelta_result(builder)
with cgutils.ifelse(builder,
cgutils.is_scalar_neg(builder, val)) as (then, otherwise):
with then:
builder.store(builder.neg(val), ret)
with otherwise:
builder.store(val, ret)
return builder.load(ret)
示例9: year_to_days
def year_to_days(builder, year_val):
"""
Given a year *year_val* (offset to 1970), return the number of days
since the 1970 epoch.
"""
# The algorithm below is copied from Numpy's get_datetimestruct_days()
# (src/multiarray/datetime.c)
ret = cgutils.alloca_once(builder, TIMEDELTA64)
# First approximation
days = scale_by_constant(builder, year_val, 365)
# Adjust for leap years
with cgutils.ifelse(builder, cgutils.is_neg_int(builder, year_val)) \
as (if_neg, if_pos):
with if_pos:
# At or after 1970:
# 1968 is the closest leap year before 1970.
# Exclude the current year, so add 1.
from_1968 = add_constant(builder, year_val, 1)
# Add one day for each 4 years
p_days = builder.add(days,
unscale_by_constant(builder, from_1968, 4))
# 1900 is the closest previous year divisible by 100
from_1900 = add_constant(builder, from_1968, 68)
# Subtract one day for each 100 years
p_days = builder.sub(p_days,
unscale_by_constant(builder, from_1900, 100))
# 1600 is the closest previous year divisible by 400
from_1600 = add_constant(builder, from_1900, 300)
# Add one day for each 400 years
p_days = builder.add(p_days,
unscale_by_constant(builder, from_1600, 400))
builder.store(p_days, ret)
with if_neg:
# Before 1970:
# NOTE `year_val` is negative, and so will be `from_1972` and `from_2000`.
# 1972 is the closest later year after 1970.
# Include the current year, so subtract 2.
from_1972 = add_constant(builder, year_val, -2)
# Subtract one day for each 4 years (`from_1972` is negative)
n_days = builder.add(days,
unscale_by_constant(builder, from_1972, 4))
# 2000 is the closest later year divisible by 100
from_2000 = add_constant(builder, from_1972, -28)
# Add one day for each 100 years
n_days = builder.sub(n_days,
unscale_by_constant(builder, from_2000, 100))
# 2000 is also the closest later year divisible by 400
# Subtract one day for each 400 years
n_days = builder.add(n_days,
unscale_by_constant(builder, from_2000, 400))
builder.store(n_days, ret)
return builder.load(ret)
示例10: store
def store(retval):
is_error = cgutils.is_null(builder, retval)
with cgutils.ifelse(builder, is_error) as (if_error, if_ok):
with if_error:
msg = context.insert_const_string(pyapi.module,
"object mode ufunc")
msgobj = pyapi.string_from_string(msg)
pyapi.err_write_unraisable(msgobj)
pyapi.decref(msgobj)
with if_ok:
# Unbox
retval = pyapi.to_native_value(retval, signature.return_type)
# Store
out.store_direct(retval, builder.load(store_offset))
示例11: impl
def impl(context, builder, sig, args):
[va, vb] = args
[ta, tb] = sig.args
ret = alloc_boolean_result(builder)
with cgutils.ifelse(builder, are_not_nat(builder, [va, vb])) as (then, otherwise):
with then:
norm_a, norm_b = normalize_timedeltas(context, builder, va, vb, ta, tb)
builder.store(builder.icmp(ll_op, norm_a, norm_b), ret)
with otherwise:
# No scaling when comparing NaT with something else
# (i.e. NaT is <= everything else, since it's the smallest
# int64 value)
builder.store(builder.icmp(ll_op, va, vb), ret)
return builder.load(ret)
示例12: from_range_state
def from_range_state(cls, context, builder, state):
"""
Create a RangeIter initialized from the given RangeState *state*.
"""
self = cls(context, builder)
start = state.start
stop = state.stop
step = state.step
startptr = cgutils.alloca_once(builder, start.type)
builder.store(start, startptr)
countptr = cgutils.alloca_once(builder, start.type)
self.iter = startptr
self.stop = stop
self.step = step
self.count = countptr
diff = builder.sub(stop, start)
zero = context.get_constant(int_type, 0)
one = context.get_constant(int_type, 1)
pos_diff = builder.icmp(lc.ICMP_SGT, diff, zero)
pos_step = builder.icmp(lc.ICMP_SGT, step, zero)
sign_differs = builder.xor(pos_diff, pos_step)
zero_step = builder.icmp(lc.ICMP_EQ, step, zero)
with cgutils.if_unlikely(builder, zero_step):
# step shouldn't be zero
context.call_conv.return_user_exc(builder, ValueError,
("range() arg 3 must not be zero",))
with cgutils.ifelse(builder, sign_differs) as (then, orelse):
with then:
builder.store(zero, self.count)
with orelse:
rem = builder.srem(diff, step)
rem = builder.select(pos_diff, rem, builder.neg(rem))
uneven = builder.icmp(lc.ICMP_SGT, rem, zero)
newcount = builder.add(builder.sdiv(diff, step),
builder.select(uneven, one, zero))
builder.store(newcount, self.count)
return self
示例13: reduce_datetime_for_unit
def reduce_datetime_for_unit(builder, dt_val, src_unit, dest_unit):
dest_unit_code = npdatetime.DATETIME_UNITS[dest_unit]
src_unit_code = npdatetime.DATETIME_UNITS[src_unit]
if dest_unit_code < 2 or src_unit_code >= 2:
return dt_val, src_unit
# Need to compute the day ordinal for *dt_val*
if src_unit_code == 0:
# Years to days
year_val = dt_val
days_val = year_to_days(builder, year_val)
else:
# Months to days
leap_array = cgutils.global_constant(builder, "leap_year_months_acc",
leap_year_months_acc)
normal_array = cgutils.global_constant(builder, "normal_year_months_acc",
normal_year_months_acc)
days = cgutils.alloca_once(builder, TIMEDELTA64)
# First compute year number and month number
year, month = cgutils.divmod_by_constant(builder, dt_val, 12)
# Then deduce the number of days
with cgutils.ifelse(builder,
is_leap_year(builder, year)) as (then, otherwise):
with then:
addend = builder.load(cgutils.gep(builder, leap_array,
0, month))
builder.store(addend, days)
with otherwise:
addend = builder.load(cgutils.gep(builder, normal_array,
0, month))
builder.store(addend, days)
days_val = year_to_days(builder, year)
days_val = builder.add(days_val, builder.load(days))
if dest_unit_code == 2:
# Need to scale back to weeks
weeks, _ = cgutils.divmod_by_constant(builder, days_val, 7)
return weeks, 'W'
else:
return days_val, 'D'
示例14: lower_expr
def lower_expr(self, expr):
if expr.op == 'binop':
return self.lower_binop(expr, inplace=False)
elif expr.op == 'inplace_binop':
return self.lower_binop(expr, inplace=True)
elif expr.op == 'unary':
value = self.loadvar(expr.value.name)
if expr.fn == '-':
res = self.pyapi.number_negative(value)
elif expr.fn == '+':
res = self.pyapi.number_positive(value)
elif expr.fn == 'not':
res = self.pyapi.object_not(value)
self.check_int_status(res)
longval = self.builder.zext(res, self.pyapi.long)
res = self.pyapi.bool_from_long(longval)
elif expr.fn == '~':
res = self.pyapi.number_invert(value)
else:
raise NotImplementedError(expr)
self.check_error(res)
return res
elif expr.op == 'call':
argvals = [self.loadvar(a.name) for a in expr.args]
fn = self.loadvar(expr.func.name)
if not expr.kws:
# No keyword
ret = self.pyapi.call_function_objargs(fn, argvals)
else:
# Have Keywords
keyvalues = [(k, self.loadvar(v.name)) for k, v in expr.kws]
args = self.pyapi.tuple_pack(argvals)
kws = self.pyapi.dict_pack(keyvalues)
ret = self.pyapi.call(fn, args, kws)
self.decref(kws)
self.decref(args)
self.check_error(ret)
return ret
elif expr.op == 'getattr':
obj = self.loadvar(expr.value.name)
res = self.pyapi.object_getattr(obj, self._freeze_string(expr.attr))
self.check_error(res)
return res
elif expr.op == 'build_tuple':
items = [self.loadvar(it.name) for it in expr.items]
res = self.pyapi.tuple_pack(items)
self.check_error(res)
return res
elif expr.op == 'build_list':
items = [self.loadvar(it.name) for it in expr.items]
res = self.pyapi.list_pack(items)
self.check_error(res)
return res
elif expr.op == 'build_map':
res = self.pyapi.dict_new(expr.size)
self.check_error(res)
return res
elif expr.op == 'build_set':
items = [self.loadvar(it.name) for it in expr.items]
res = self.pyapi.set_new()
self.check_error(res)
for it in items:
ok = self.pyapi.set_add(res, it)
self.check_int_status(ok)
return res
elif expr.op == 'getiter':
obj = self.loadvar(expr.value.name)
res = self.pyapi.object_getiter(obj)
self.check_error(res)
return res
elif expr.op == 'iternext':
iterobj = self.loadvar(expr.value.name)
item = self.pyapi.iter_next(iterobj)
is_valid = cgutils.is_not_null(self.builder, item)
pair = self.pyapi.tuple_new(2)
with cgutils.ifelse(self.builder, is_valid) as (then, otherwise):
with then:
self.pyapi.tuple_setitem(pair, 0, item)
with otherwise:
self.check_occurred()
# Make the tuple valid by inserting None as dummy
# iteration "result" (it will be ignored).
self.pyapi.tuple_setitem(pair, 0, self.pyapi.make_none())
self.pyapi.tuple_setitem(pair, 1, self.pyapi.bool_from_bool(is_valid))
return pair
elif expr.op == 'pair_first':
pair = self.loadvar(expr.value.name)
first = self.pyapi.tuple_getitem(pair, 0)
self.incref(first)
return first
elif expr.op == 'pair_second':
pair = self.loadvar(expr.value.name)
second = self.pyapi.tuple_getitem(pair, 1)
self.incref(second)
return second
elif expr.op == 'exhaust_iter':
iterobj = self.loadvar(expr.value.name)
tup = self.pyapi.sequence_tuple(iterobj)
self.check_error(tup)
#.........这里部分代码省略.........
示例15: build_ufunc_wrapper
def build_ufunc_wrapper(library, context, func, signature, objmode, env):
"""
Wrap the scalar function with a loop that iterates over the arguments
"""
byte_t = Type.int(8)
byte_ptr_t = Type.pointer(byte_t)
byte_ptr_ptr_t = Type.pointer(byte_ptr_t)
intp_t = context.get_value_type(types.intp)
intp_ptr_t = Type.pointer(intp_t)
fnty = Type.function(Type.void(), [byte_ptr_ptr_t, intp_ptr_t,
intp_ptr_t, byte_ptr_t])
wrapper_module = library.create_ir_module('')
if objmode:
func_type = context.call_conv.get_function_type(
types.pyobject, [types.pyobject] * len(signature.args))
else:
func_type = context.call_conv.get_function_type(
signature.return_type, signature.args)
oldfunc = func
func = wrapper_module.add_function(func_type,
name=func.name)
func.attributes.add("alwaysinline")
wrapper = wrapper_module.add_function(fnty, "__ufunc__." + func.name)
arg_args, arg_dims, arg_steps, arg_data = wrapper.args
arg_args.name = "args"
arg_dims.name = "dims"
arg_steps.name = "steps"
arg_data.name = "data"
builder = Builder.new(wrapper.append_basic_block("entry"))
loopcount = builder.load(arg_dims, name="loopcount")
# Prepare inputs
arrays = []
for i, typ in enumerate(signature.args):
arrays.append(UArrayArg(context, builder, arg_args, arg_steps, i, typ))
# Prepare output
out = UArrayArg(context, builder, arg_args, arg_steps, len(arrays),
signature.return_type)
# Setup indices
offsets = []
zero = context.get_constant(types.intp, 0)
for _ in arrays:
p = cgutils.alloca_once(builder, intp_t)
offsets.append(p)
builder.store(zero, p)
store_offset = cgutils.alloca_once(builder, intp_t)
builder.store(zero, store_offset)
unit_strided = cgutils.true_bit
for ary in arrays:
unit_strided = builder.and_(unit_strided, ary.is_unit_strided)
if objmode:
# General loop
pyapi = context.get_python_api(builder)
gil = pyapi.gil_ensure()
with cgutils.for_range(builder, loopcount, intp=intp_t):
slowloop = build_obj_loop_body(context, func, builder,
arrays, out, offsets,
store_offset, signature,
pyapi, env)
pyapi.gil_release(gil)
builder.ret_void()
else:
with cgutils.ifelse(builder, unit_strided) as (is_unit_strided,
is_strided):
with is_unit_strided:
with cgutils.for_range(builder, loopcount, intp=intp_t) as ind:
fastloop = build_fast_loop_body(context, func, builder,
arrays, out, offsets,
store_offset, signature,
ind)
builder.ret_void()
with is_strided:
# General loop
with cgutils.for_range(builder, loopcount, intp=intp_t):
slowloop = build_slow_loop_body(context, func, builder,
arrays, out, offsets,
store_offset, signature)
builder.ret_void()
builder.ret_void()
del builder
# Run optimizer
library.add_ir_module(wrapper_module)
#.........这里部分代码省略.........