Python operator.mul() Examples
The following are 30
code examples of operator.mul().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
operator
, or try the search function
.
Example #1
Source File: ops.py From recruit with Apache License 2.0 | 6 votes |
def add_flex_arithmetic_methods(cls): """ Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``) to the class. Parameters ---------- cls : class flex methods will be defined and pinned to this class """ flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls) new_methods = _create_methods(cls, flex_arith_method, flex_comp_method, bool_method=None, special=False) new_methods.update(dict(multiply=new_methods['mul'], subtract=new_methods['sub'], divide=new_methods['div'])) # opt out of bool flex methods for now assert not any(kname in new_methods for kname in ('ror_', 'rxor', 'rand_')) add_methods(cls, new_methods=new_methods) # ----------------------------------------------------------------------------- # Series
Example #2
Source File: xrft.py From xrft with MIT License | 6 votes |
def _apply_window(da, dims, window_type='hanning'): """Creating windows in dimensions dims.""" if window_type not in ['hanning']: raise NotImplementedError("Only hanning window is supported for now.") numpy_win_func = getattr(np, window_type) if da.chunks: def dask_win_func(n): return dsar.from_delayed( delayed(numpy_win_func, pure=True)(n), (n,), float) win_func = dask_win_func else: win_func = numpy_win_func windows = [xr.DataArray(win_func(len(da[d])), dims=da[d].dims, coords=da[d].coords) for d in dims] return da * reduce(operator.mul, windows[::-1])
Example #3
Source File: rl.py From fine-lm with MIT License | 6 votes |
def feed_forward_categorical_fun(action_space, config, observations): """Feed-forward categorical.""" if not isinstance(action_space, gym.spaces.Discrete): raise ValueError("Expecting discrete action space.") flat_observations = tf.reshape(observations, [ tf.shape(observations)[0], tf.shape(observations)[1], functools.reduce(operator.mul, observations.shape.as_list()[2:], 1)]) with tf.variable_scope("network_parameters"): with tf.variable_scope("policy"): x = flat_observations for size in config.policy_layers: x = tf.contrib.layers.fully_connected(x, size, tf.nn.relu) logits = tf.contrib.layers.fully_connected(x, action_space.n, activation_fn=None) with tf.variable_scope("value"): x = flat_observations for size in config.value_layers: x = tf.contrib.layers.fully_connected(x, size, tf.nn.relu) value = tf.contrib.layers.fully_connected(x, 1, None)[..., 0] policy = tf.contrib.distributions.Categorical(logits=logits) return NetworkOutput(policy, value, lambda a: a)
Example #4
Source File: rl.py From fine-lm with MIT License | 6 votes |
def dense_bitwise_categorical_fun(action_space, config, observations): """Dense network with bitwise input and categorical output.""" del config obs_shape = common_layers.shape_list(observations) x = tf.reshape(observations, [-1] + obs_shape[2:]) with tf.variable_scope("network_parameters"): with tf.variable_scope("dense_bitwise"): x = discretization.int_to_bit_embed(x, 8, 32) flat_x = tf.reshape( x, [obs_shape[0], obs_shape[1], functools.reduce(operator.mul, x.shape.as_list()[1:], 1)]) x = tf.contrib.layers.fully_connected(flat_x, 256, tf.nn.relu) x = tf.contrib.layers.fully_connected(flat_x, 128, tf.nn.relu) logits = tf.contrib.layers.fully_connected(x, action_space.n, activation_fn=None) value = tf.contrib.layers.fully_connected( x, 1, activation_fn=None)[..., 0] policy = tf.contrib.distributions.Categorical(logits=logits) return NetworkOutput(policy, value, lambda a: a)
Example #5
Source File: loader.py From vergeml with MIT License | 6 votes |
def begin_read_samples(self): if self.cache: return self.input.begin_read_samples() # copy meta if self.output: self.output.meta = self.input.meta self.multipliers = {} self.rngs = {} def _mul(split): return reduce(operator.mul, map(lambda op: _get_multiplier(split, op), self.ops), 1) for split in SPLITS: self.multipliers[split] = _mul(split) self.cache[split] = self._calculate_num_samples(split) self.rngs[split] = self.cache[split] * [None] self.input.end_read_samples()
Example #6
Source File: common_attention.py From fine-lm with MIT License | 6 votes |
def gather_indices_2d(x, block_shape, block_stride): """Getting gather indices.""" # making an identity matrix kernel kernel = tf.eye(block_shape[0] * block_shape[1]) kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1]) # making indices [1, h, w, 1] to appy convs x_shape = common_layers.shape_list(x) indices = tf.range(x_shape[2] * x_shape[3]) indices = tf.reshape(indices, [1, x_shape[2], x_shape[3], 1]) indices = tf.nn.conv2d( tf.cast(indices, tf.float32), kernel, strides=[1, block_stride[0], block_stride[1], 1], padding="VALID") # making indices [num_blocks, dim] to gather dims = common_layers.shape_list(indices)[:3] if all([isinstance(dim, int) for dim in dims]): num_blocks = functools.reduce(operator.mul, dims, 1) else: num_blocks = tf.reduce_prod(dims) indices = tf.reshape(indices, [num_blocks, -1]) return tf.cast(indices, tf.int32)
Example #7
Source File: wallet.py From tensortrade with Apache License 2.0 | 6 votes |
def create_wallet_source(wallet: Wallet, include_worth=True): exchange_name = wallet.exchange.name symbol = wallet.instrument.symbol with Module(exchange_name + ":/" + symbol) as wallet_ds: free_balance = Lambda(lambda w: w.balance.as_float(), wallet, name="free") locked_balance = Lambda(lambda w: w.locked_balance.as_float(), wallet, name="locked") total_balance = Lambda(lambda w: w.total_balance.as_float(), wallet, name="total") nodes = [free_balance, locked_balance, total_balance] if include_worth: price = Select(lambda node: node.name.endswith(symbol))(wallet.exchange) worth = BinOp(operator.mul, name="worth")(price, total_balance) nodes += [worth] return wallet_ds
Example #8
Source File: fft.py From scarlet with MIT License | 6 votes |
def _kspace_operation(image1, image2, padding, op, shape, axes): """Combine two images in k-space using a given `operator` `image1` and `image2` are required to be `Fourier` objects and `op` should be an operator (either `operator.mul` for a convolution or `operator.truediv` for deconvolution). `shape` is the shape of the output image (`Fourier` instance). """ if len(image1.shape) != len(image2.shape): msg = "Both images must have the same number of axes, got {0} and {1}" raise Exception(msg.format(len(image1.shape), len(image2.shape))) fft_shape = _get_fft_shape(image1.image, image2.image, padding, axes) convolved_fft = op(image1.fft(fft_shape, axes), image2.fft(fft_shape, axes)) # why is shape not image1.shape? images are never padded convolved = Fourier.from_fft(convolved_fft, fft_shape, shape, axes) return convolved
Example #9
Source File: fft.py From scarlet with MIT License | 6 votes |
def convolve(image1, image2, padding=3, axes=(-2, -1)): """Convolve two images Parameters ---------- image1: `Fourier` `Fourier` object represeting the image and it's FFT. image2: `Fourier` `Fourier` object represeting the image and it's FFT. padding: int Additional padding to use when generating the FFT to supress artifacts. """ return _kspace_operation( image1, image2, padding, operator.mul, image1.shape, axes=axes )
Example #10
Source File: test_core.py From recruit with Apache License 2.0 | 6 votes |
def test_datafriendly_mul(self): # Test keeping data w/ (inplace) multiplication # Test mul w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) xx = x * 2 assert_equal(xx.data, [2, 4, 3]) assert_equal(xx.mask, [0, 0, 1]) # Test imul w/ scalar x = array([1, 2, 3], mask=[0, 0, 1]) x *= 2 assert_equal(x.data, [2, 4, 3]) assert_equal(x.mask, [0, 0, 1]) # Test mul w/ array x = array([1, 2, 3], mask=[0, 0, 1]) xx = x * array([10, 20, 30], mask=[1, 0, 0]) assert_equal(xx.data, [1, 40, 3]) assert_equal(xx.mask, [1, 0, 1]) # Test imul w/ array x = array([1, 2, 3], mask=[0, 0, 1]) x *= array([10, 20, 30], mask=[1, 0, 0]) assert_equal(x.data, [1, 40, 3]) assert_equal(x.mask, [1, 0, 1])
Example #11
Source File: test_extint128.py From recruit with Apache License 2.0 | 6 votes |
def test_safe_binop(): # Test checked arithmetic routines ops = [ (operator.add, 1), (operator.sub, 2), (operator.mul, 3) ] with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it: for xop, a, b in it: pyop, op = xop c = pyop(a, b) if not (INT64_MIN <= c <= INT64_MAX): assert_raises(OverflowError, mt.extint_safe_binop, a, b, op) else: d = mt.extint_safe_binop(a, b, op) if c != d: # assert_equal is slow assert_equal(d, c)
Example #12
Source File: test_classes.py From recruit with Apache License 2.0 | 6 votes |
def test_mul(Poly): c1 = list(random((4,)) + .5) c2 = list(random((3,)) + .5) p1 = Poly(c1) p2 = Poly(c2) p3 = p1 * p2 assert_poly_almost_equal(p2 * p1, p3) assert_poly_almost_equal(p1 * c2, p3) assert_poly_almost_equal(c2 * p1, p3) assert_poly_almost_equal(p1 * tuple(c2), p3) assert_poly_almost_equal(tuple(c2) * p1, p3) assert_poly_almost_equal(p1 * np.array(c2), p3) assert_poly_almost_equal(np.array(c2) * p1, p3) assert_poly_almost_equal(p1 * 2, p1 * Poly([2])) assert_poly_almost_equal(2 * p1, p1 * Poly([2])) assert_raises(TypeError, op.mul, p1, Poly([0], domain=Poly.domain + 1)) assert_raises(TypeError, op.mul, p1, Poly([0], window=Poly.window + 1)) if Poly is Polynomial: assert_raises(TypeError, op.mul, p1, Chebyshev([0])) else: assert_raises(TypeError, op.mul, p1, Polynomial([0]))
Example #13
Source File: test_panel.py From recruit with Apache License 2.0 | 6 votes |
def test_arith(self): self._test_op(self.panel, operator.add) self._test_op(self.panel, operator.sub) self._test_op(self.panel, operator.mul) self._test_op(self.panel, operator.truediv) self._test_op(self.panel, operator.floordiv) self._test_op(self.panel, operator.pow) self._test_op(self.panel, lambda x, y: y + x) self._test_op(self.panel, lambda x, y: y - x) self._test_op(self.panel, lambda x, y: y * x) self._test_op(self.panel, lambda x, y: y / x) self._test_op(self.panel, lambda x, y: y ** x) self._test_op(self.panel, lambda x, y: x + y) # panel + 1 self._test_op(self.panel, lambda x, y: x - y) # panel - 1 self._test_op(self.panel, lambda x, y: x * y) # panel * 1 self._test_op(self.panel, lambda x, y: x / y) # panel / 1 self._test_op(self.panel, lambda x, y: x ** y) # panel ** 1 pytest.raises(Exception, self.panel.__add__, self.panel['ItemA'])
Example #14
Source File: test_panel.py From recruit with Apache License 2.0 | 6 votes |
def test_arith_flex_panel(self): ops = ['add', 'sub', 'mul', 'div', 'truediv', 'pow', 'floordiv', 'mod'] if not compat.PY3: aliases = {} else: aliases = {'div': 'truediv'} self.panel = self.panel.to_panel() for n in [np.random.randint(-50, -1), np.random.randint(1, 50), 0]: for op in ops: alias = aliases.get(op, op) f = getattr(operator, alias) exp = f(self.panel, n) result = getattr(self.panel, op)(n) assert_panel_equal(result, exp, check_panel_type=True) # rops r_f = lambda x, y: f(y, x) exp = r_f(self.panel, n) result = getattr(self.panel, 'r' + op)(n) assert_panel_equal(result, exp)
Example #15
Source File: test_series.py From recruit with Apache License 2.0 | 6 votes |
def test_binary_operators(self): # skipping for now ##### import pytest pytest.skip("skipping sparse binary operators test") def _check_inplace_op(iop, op): tmp = self.bseries.copy() expected = op(tmp, self.bseries) iop(tmp, self.bseries) tm.assert_sp_series_equal(tmp, expected) inplace_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow'] for op in inplace_ops: _check_inplace_op(getattr(operator, "i%s" % op), getattr(operator, op))
Example #16
Source File: base.py From recruit with Apache License 2.0 | 6 votes |
def _add_arithmetic_ops(cls): cls.__add__ = cls._create_arithmetic_method(operator.add) cls.__radd__ = cls._create_arithmetic_method(ops.radd) cls.__sub__ = cls._create_arithmetic_method(operator.sub) cls.__rsub__ = cls._create_arithmetic_method(ops.rsub) cls.__mul__ = cls._create_arithmetic_method(operator.mul) cls.__rmul__ = cls._create_arithmetic_method(ops.rmul) cls.__pow__ = cls._create_arithmetic_method(operator.pow) cls.__rpow__ = cls._create_arithmetic_method(ops.rpow) cls.__mod__ = cls._create_arithmetic_method(operator.mod) cls.__rmod__ = cls._create_arithmetic_method(ops.rmod) cls.__floordiv__ = cls._create_arithmetic_method(operator.floordiv) cls.__rfloordiv__ = cls._create_arithmetic_method(ops.rfloordiv) cls.__truediv__ = cls._create_arithmetic_method(operator.truediv) cls.__rtruediv__ = cls._create_arithmetic_method(ops.rtruediv) if not PY3: cls.__div__ = cls._create_arithmetic_method(operator.div) cls.__rdiv__ = cls._create_arithmetic_method(ops.rdiv) cls.__divmod__ = cls._create_arithmetic_method(divmod) cls.__rdivmod__ = cls._create_arithmetic_method(ops.rdivmod)
Example #17
Source File: base.py From recruit with Apache License 2.0 | 6 votes |
def _add_numeric_methods_binary(cls): """ Add in numeric methods. """ cls.__add__ = _make_arithmetic_op(operator.add, cls) cls.__radd__ = _make_arithmetic_op(ops.radd, cls) cls.__sub__ = _make_arithmetic_op(operator.sub, cls) cls.__rsub__ = _make_arithmetic_op(ops.rsub, cls) cls.__rpow__ = _make_arithmetic_op(ops.rpow, cls) cls.__pow__ = _make_arithmetic_op(operator.pow, cls) cls.__truediv__ = _make_arithmetic_op(operator.truediv, cls) cls.__rtruediv__ = _make_arithmetic_op(ops.rtruediv, cls) if not compat.PY3: cls.__div__ = _make_arithmetic_op(operator.div, cls) cls.__rdiv__ = _make_arithmetic_op(ops.rdiv, cls) # TODO: rmod? rdivmod? cls.__mod__ = _make_arithmetic_op(operator.mod, cls) cls.__floordiv__ = _make_arithmetic_op(operator.floordiv, cls) cls.__rfloordiv__ = _make_arithmetic_op(ops.rfloordiv, cls) cls.__divmod__ = _make_arithmetic_op(divmod, cls) cls.__mul__ = _make_arithmetic_op(operator.mul, cls) cls.__rmul__ = _make_arithmetic_op(ops.rmul, cls)
Example #18
Source File: ops.py From recruit with Apache License 2.0 | 6 votes |
def _get_frame_op_default_axis(name): """ Only DataFrame cares about default_axis, specifically: special methods have default_axis=None and flex methods have default_axis='columns'. Parameters ---------- name : str Returns ------- default_axis: str or None """ if name.replace('__r', '__') in ['__and__', '__or__', '__xor__']: # bool methods return 'columns' elif name.startswith('__'): # __add__, __mul__, ... return None else: # add, mul, ... return 'columns'
Example #19
Source File: loader.py From vergeml with MIT License | 5 votes |
def _calculate_num_samples(self, split): """Calculate the total number of samples after applying ops. """ num_samples = self.input.num_samples(split) # calculate how much the samples will be augmented after going through ops multiplier = reduce(operator.mul, map(lambda op: _get_multiplier(split, op), self.ops), 1) return int(num_samples * multiplier)
Example #20
Source File: test_arithmetic.py From recruit with Apache License 2.0 | 5 votes |
def test_arith_flex_series(self, simple_frame): df = simple_frame row = df.xs('a') col = df['two'] # after arithmetic refactor, add truediv here ops = ['add', 'sub', 'mul', 'mod'] for op in ops: f = getattr(df, op) op = getattr(operator, op) tm.assert_frame_equal(f(row), op(df, row)) tm.assert_frame_equal(f(col, axis=0), op(df.T, col).T) # special case for some reason tm.assert_frame_equal(df.add(row, axis=None), df + row) # cases which will be refactored after big arithmetic refactor tm.assert_frame_equal(df.div(row), df / row) tm.assert_frame_equal(df.div(col, axis=0), (df.T / col).T) # broadcasting issue in GH 7325 df = pd.DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype='int64') expected = pd.DataFrame([[np.nan, np.inf], [1.0, 1.5], [1.0, 1.25]]) result = df.div(df[0], axis='index') tm.assert_frame_equal(result, expected) df = pd.DataFrame(np.arange(3 * 2).reshape((3, 2)), dtype='float64') expected = pd.DataFrame([[np.nan, np.inf], [1.0, 1.5], [1.0, 1.25]]) result = df.div(df[0], axis='index') tm.assert_frame_equal(result, expected)
Example #21
Source File: ndarray.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def __bool__(self): num_elements = reduce(operator.mul, self.shape, 1) if num_elements == 0: return False elif num_elements == 1: return bool(self.asscalar()) else: raise ValueError("The truth value of an NDArray with multiple elements " \ "is ambiguous.")
Example #22
Source File: test_numeric.py From recruit with Apache License 2.0 | 5 votes |
def test_binops(self): ops = [operator.add, operator.sub, operator.mul, operator.floordiv, operator.truediv] scalars = [-1, 1, 2] idxs = [pd.RangeIndex(0, 10, 1), pd.RangeIndex(0, 20, 2), pd.RangeIndex(-10, 10, 2), pd.RangeIndex(5, -5, -1)] self.check_binop(ops, scalars, idxs)
Example #23
Source File: utils_mnist.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 5 votes |
def download_and_parse_mnist_file(file_name, datadir=None, force=False): file_name = maybe_download_mnist_file(file_name, datadir=datadir, force=force) # Open the file and unzip it if necessary if os.path.splitext(file_name)[1] == '.gz': open_fn = gzip.open else: open_fn = open # Parse the file with open_fn(file_name, 'rb') as file_descriptor: header = file_descriptor.read(4) assert len(header) == 4 zeros, data_type, n_dims = struct.unpack('>HBB', header) assert zeros == 0 hex_to_data_type = { 0x08: 'B', 0x09: 'b', 0x0b: 'h', 0x0c: 'i', 0x0d: 'f', 0x0e: 'd'} data_type = hex_to_data_type[data_type] dim_sizes = struct.unpack( '>' + 'I' * n_dims, file_descriptor.read(4 * n_dims)) data = array.array(data_type, file_descriptor.read()) data.byteswap() desired_items = functools.reduce(operator.mul, dim_sizes) assert len(data) == desired_items return np.array(data).reshape(dim_sizes)
Example #24
Source File: multiples-of-3-and-5.py From interview-with-python with MIT License | 5 votes |
def getSumOfMultiples(multiples, limit): result = 0 sign = 1 for i in range(1, len(multiples) + 1): for x in combinations(multiples, i): result += sign * getSumOfMultiple(reduce(mul, x, 1), limit) sign *= -1 return result
Example #25
Source File: statistics.py From appmetrics with Apache License 2.0 | 5 votes |
def geometric_mean(data): """Return the geometric mean of data """ if not data: raise StatisticsError('geometric_mean requires at least one data point') # in order to support negative or null values data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data] return math.pow(math.fabs(functools.reduce(operator.mul, data)), 1.0 / len(data))
Example #26
Source File: multiply.py From mars with Apache License 2.0 | 5 votes |
def mul(df, other, axis='columns', level=None, fill_value=None): op = DataFrameMul(axis=axis, level=level, fill_value=fill_value, lhs=df, rhs=other) return op(df, other)
Example #27
Source File: core.py From mars with Apache License 2.0 | 5 votes |
def nannumel(x, **kwargs): x_size = reduce(operator.mul, x.shape) xp = get_array_module(x) return x_size - xp.sum(xp.isnan(x), **kwargs)
Example #28
Source File: core.py From mars with Apache License 2.0 | 5 votes |
def _largest_chunk_size(nsplits): return reduce(operator.mul, map(max, nsplits))
Example #29
Source File: core.py From mars with Apache License 2.0 | 5 votes |
def _chunk_number(nsplits): return reduce(operator.mul, map(len, nsplits))
Example #30
Source File: loader.py From vergeml with MIT License | 5 votes |
def perform_read(self, split: str, index: int, n_samples: int = 1): # pylint: disable=R0914 mul = self.multipliers[split] offset = int(index % mul) start_index = int(index/mul) end_index = int((index+n_samples)/mul) read = max(1, int(n_samples/mul) + int(min(1, index%mul))) res = [] samples = self.input.read_samples(split, start_index, read) if self.output and self.ops: op1, *oprest = self.ops for sample in samples: res.extend(op1.process(sample, oprest)) else: res = samples if self.output and self.transform: res = [self.output.transform(sample) for sample in res] for sample, i in zip(res, range(start_index, end_index)): if self.rngs[split][i] is None: self.rngs[split][i] = sample.rng else: sample.rng = self.rngs[split][i] res = res[offset: offset+n_samples] return list(map(lambda s: ((s.x, s.y), (s.meta, s.rng)), res))