我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.floor_divide()。
def test_remainder_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): if sg1 == -1 and dt1 in np.typecodes['UnsignedInteger']: continue if sg2 == -1 and dt2 in np.typecodes['UnsignedInteger']: continue fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*71, dtype=dt1) b = np.array(sg2*19, dtype=dt2) div = np.floor_divide(a, b) rem = np.remainder(a, b) assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def test_float_remainder_exact(self): # test that float results are exact for small integers. This also # holds for the same integers scaled by powers of two. nlst = list(range(-127, 0)) plst = list(range(1, 128)) dividend = nlst + [0] + plst divisor = nlst + plst arg = list(itertools.product(dividend, divisor)) tgt = list(divmod(*t) for t in arg) a, b = np.array(arg, dtype=int).T # convert exact integer results from Python to float so that # signed zero can be used, it is checked. tgtdiv, tgtrem = np.array(tgt, dtype=float).T tgtdiv = np.where((tgtdiv == 0.0) & ((b < 0) ^ (a < 0)), -0.0, tgtdiv) tgtrem = np.where((tgtrem == 0.0) & (b < 0), -0.0, tgtrem) for dt in np.typecodes['Float']: msg = 'dtype: %s' % (dt,) fa = a.astype(dt) fb = b.astype(dt) div = np.floor_divide(fa, fb) rem = np.remainder(fa, fb) assert_equal(div, tgtdiv, err_msg=msg) assert_equal(rem, tgtrem, err_msg=msg)
def test_float_remainder_roundoff(self): # gh-6127 dt = np.typecodes['Float'] for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product((+1, -1), (+1, -1)): fmt = 'dt1: %s, dt2: %s, sg1: %s, sg2: %s' msg = fmt % (dt1, dt2, sg1, sg2) a = np.array(sg1*78*6e-8, dtype=dt1) b = np.array(sg2*6e-8, dtype=dt2) div = np.floor_divide(a, b) rem = np.remainder(a, b) # Equal assertion should hold when fmod is used assert_equal(div*b + rem, a, err_msg=msg) if sg2 == -1: assert_(b < rem <= 0, msg) else: assert_(b > rem >= 0, msg)
def test_NotImplemented_not_returned(self): # See gh-5964 and gh-2091. Some of these functions are not operator # related and were fixed for other reasons in the past. binary_funcs = [ np.power, np.add, np.subtract, np.multiply, np.divide, np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or, np.bitwise_xor, np.left_shift, np.right_shift, np.fmax, np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2, np.logical_and, np.logical_or, np.logical_xor, np.maximum, np.minimum, np.mod ] # These functions still return NotImplemented. Will be fixed in # future. # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal] a = np.array('1') b = 1 for f in binary_funcs: assert_raises(TypeError, f, a, b)
def __ifloordiv__(self, other): """ Floor divide self by other in-place. """ other_data = getdata(other) dom_mask = _DomainSafeDivide().__call__(self._data, other_data) other_mask = getmask(other) new_mask = mask_or(other_mask, dom_mask) # The following 3 lines control the domain filling if dom_mask.any(): (_, fval) = ufunc_fills[np.floor_divide] other_data = np.where(dom_mask, fval, other_data) self._mask |= new_mask self._data.__ifloordiv__(np.where(self._mask, self.dtype.type(1), other_data)) return self
def calc_l1_norm_itae(meas_values, desired_values, step_width): """ Calculate the L1-Norm of the ITAE (Integral of Time-multiplied Absolute value of Error). Args: step_width (float): Time difference between measurements. desired_values (array-like): Desired values. meas_values (array-like): Measured values. """ def e_func(_t): _idx = np.floor_divide(_t, step_width).astype(int) e = t * np.abs(desired_values[_idx, ..., 0] - meas_values[_idx, ..., 0]) return e t = np.array([x * step_width for x in range(len(desired_values))]) err = e_func(t) l1norm_itae = simps(err, t) return l1norm_itae
def calc_l1_norm_abs(meas_values, desired_values, step_width): """ Calculate the L1-Norm of the absolute error. Args: step_width (float): Time difference between measurements. desired_values (array-like): Desired values. meas_values (array-like): Measured values. """ def e_func(_t): _idx = np.floor_divide(_t, step_width).astype(int) e = np.abs(desired_values[_idx, ..., 0] - meas_values[_idx, ..., 0]) return e t = np.array([x * step_width for x in range(len(desired_values))]) err = e_func(t) l1norm_abs = simps(err, t) return l1norm_abs
def _window_slicing_sequence(self, X, window, shape_1X, y=None, stride=1): """ Slicing procedure for sequences (aka shape_1X = [.., 1]). :param X: np.array Array containing the input samples. Must be of shape [n_samples, data] where data is a 1D array. :param window: int Size of the window to use for slicing. :param shape_1X: list or np.array Shape of a single sample [n_lines, n_col]. :param y: np.array (default=None) Target values. :param stride: int (default=1) Step used when slicing the data. :return: np.array and np.array Arrays containing the sliced sequences and target values (empty if 'y' is None). """ if shape_1X[1] < window: raise ValueError('window must be smaller than the sequence dimension') len_iter = np.floor_divide((shape_1X[1] - window), stride) + 1 iter_array = np.arange(0, stride*len_iter, stride) ind_1X = np.arange(np.prod(shape_1X)) inds_to_take = [ind_1X[i:i+window] for i in iter_array] sliced_sqce = np.take(X, inds_to_take, axis=1).reshape(-1, window) if y is not None: sliced_target = np.repeat(y, len_iter) elif y is None: sliced_target = None return sliced_sqce, sliced_target
def lab2npy(input_path, out, frame_rate= 0.01): """ frame_rate : sampling rate, typically 10 ms (or 0.01s) """ name=os.path.basename(input_path) df=pd.read_table(input_path, sep=" ", header=None) df.columns=["onset", "offset", "phone", "score"] #onset and offset are in 100* nanosecond. Need to be put in second df["onset"]=df["onset"]*10**(-7) df["offset"]=df["offset"]*10**(-7) phones=['a{}'.format(i) for i in range(1, 49)] list_feats=[] R=np.empty(1) R[0]=frame_rate for i in range(len(df)): on=df["onset"].iloc[i] off=df["offset"].iloc[i] nb_frame=int(np.floor_divide((off-on),R[0])) for ff in range(nb_frame): one_hot=np.empty(len(phones)) for j in range(len(phones)): if df["phone"][i]==phones[j]: one_hot[j]=1 else: one_hot[j]=0 list_feats.append(one_hot) arr_feats = np.array(list_feats) directory=out + "/npy/" try: os.stat(directory) except: os.mkdir(directory) np.save(directory + "/"+ name.split(".")[0], arr=arr_feats, allow_pickle=False)
def test_floor_division_complex(self): # check that implementation is correct msg = "Complex floor division implementation check" x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128) y = np.array([0., -1., 0., 0.], dtype=np.complex128) assert_equal(np.floor_divide(x**2, x), y, err_msg=msg) # check overflow, underflow msg = "Complex floor division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = np.floor_divide(x**2, x) assert_equal(y, [1.e+110, 0], err_msg=msg)
def __floordiv__(self, other): """ Divide other into self, and return a new masked array. """ if self._delegate_binop(other): return NotImplemented return floor_divide(self, other)
def __rfloordiv__(self, other): """ Divide self into other, and return a new masked array. """ return floor_divide(other, self)
def int_div(x1: Number = 1.0, x2: Number = 2.0) -> Int: return np.floor_divide(x1, x2)
def __floordiv__(self, other): return floor_divide(self, other)
def __ifloordiv__(self, other): return floor_divide(self, other, self)
def __rfloordiv__(self, other): return floor_divide(other, self)
def generate_op(self, op, out, x, y): self.append("np.floor_divide({}, {}, out={})", x, y, out)
def vox_to_pos(self, vox): return np.floor_divide(vox - self.MOVE_GRID_OFFSET, self.MOVE_DELTA).astype(np.int64)
def get_output_margin(model_config): return np.floor_divide(model_config.input_fov_shape - model_config.output_fov_shape, 2)
def __init__(self, volume, shape, label_margin=None): self.volume = volume self.shape = shape self.margin = np.floor_divide(self.shape, 2).astype(np.int64) if label_margin is None: label_margin = np.zeros(3, dtype=np.int64) self.label_margin = label_margin self.skip_blank_sections = True self.ctr_min = self.margin self.ctr_max = (np.array(self.volume.shape) - self.margin - 1).astype(np.int64) self.random = np.random.RandomState(CONFIG.random_seed) # If the volume has a mask channel, further limit ctr_min and # ctr_max to lie inside a margin in the AABB of the mask. if self.volume.mask_data is not None: mask_min, mask_max = self.volume.mask_bounds mask_min = self.volume.local_coord_to_world(mask_min) mask_max = self.volume.local_coord_to_world(mask_max) self.ctr_min = np.maximum(self.ctr_min, mask_min + self.label_margin) self.ctr_max = np.minimum(self.ctr_max, mask_max - self.label_margin - 1) if np.any(self.ctr_min >= self.ctr_max): raise ValueError('Cannot generate subvolume bounds: bounds ({}, {}) too small for shape ({})'.format( np.array_str(self.ctr_min), np.array_str(self.ctr_max), np.array_str(self.shape)))
def __init__(self, parent, partitioning, partition_index): super(PartitionedVolume, self).__init__( parent, parent.resolution, image_data=parent.image_data, label_data=parent.label_data, mask_data=parent.mask_data) self.partitioning = np.asarray(partitioning) self.partition_index = np.asarray(partition_index) partition_shape = np.floor_divide(np.array(self.parent.shape), self.partitioning) self.bounds = ((np.multiply(partition_shape, self.partition_index)).astype(np.int64), (np.multiply(partition_shape, self.partition_index + 1)).astype(np.int64))
def shape(self): return tuple(np.floor_divide(np.array(self.parent.shape), self.scale))
def __ifloordiv__(self, other): """ See __div__. """ oth = sanitize_units_mul(self, other) np.floor_divide(self, oth, out=self) return self
def plot_minute_histogram(splits): def plot(ax, detections): bins = np.floor_divide(detections['timestamp'], 60).astype('int64') counts = np.bincount(bins) ax.plot(counts) ax.set_xlabel('Minute') ax.set_ylabel('Count') fig = plt.figure() plot_rxtx_matrix(fig, splits, plot) fig.suptitle('Histogram of number of detections per minute')