Python numpy.mod() Examples
The following are 30
code examples of numpy.mod().
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
numpy
, or try the search function
.
Example #1
Source File: dp.py From pytorch_stacked_hourglass with BSD 3-Clause "New" or "Revised" License | 6 votes |
def preprocess(self, data): # random hue and saturation data = cv2.cvtColor(data, cv2.COLOR_RGB2HSV); delta = (np.random.random() * 2 - 1) * 0.2 data[:, :, 0] = np.mod(data[:,:,0] + (delta * 360 + 360.), 360.) delta_sature = np.random.random() + 0.5 data[:, :, 1] *= delta_sature data[:,:, 1] = np.maximum( np.minimum(data[:,:,1], 1), 0 ) data = cv2.cvtColor(data, cv2.COLOR_HSV2RGB) # adjust brightness delta = (np.random.random() * 2 - 1) * 0.3 data += delta # adjust contrast mean = data.mean(axis=2, keepdims=True) data = (data - mean) * (np.random.random() + 0.5) + mean data = np.minimum(np.maximum(data, 0), 1) return data
Example #2
Source File: lattice.py From tenpy with GNU General Public License v3.0 | 6 votes |
def mps2lat_idx(self, i): """Translate MPS index `i` to lattice indices ``(x_0, ..., x_{dim-1}, u)``. Parameters ---------- i : int | array_like of int MPS index/indices. Returns ------- lat_idx : array First dimensions like `i`, last dimension has len `dim`+1 and contains the lattice indices ``(x_0, ..., x_{dim-1}, u)`` corresponding to `i`. For `i` accross the MPS unit cell and "infinite" `bc_MPS`, we shift `x_0` accordingly. """ if self.bc_MPS == 'infinite': # allow `i` outsit of MPS unit cell for bc_MPS infinite i0 = i i = np.mod(i, self.N_sites) if np.any(i0 != i): lat = self.order[i].copy() lat[..., 0] += (i0 - i) * self.N_rings // self.N_sites # N_sites_per_ring might not be set for IrregularLattice return lat return self.order[i].copy()
Example #3
Source File: lattice.py From tenpy with GNU General Public License v3.0 | 6 votes |
def get_lattice(lattice_name): """Given the name of a :class:`Lattice` class, get the lattice class itself. Parameters ---------- lattice_name : str Name of a :class:`Lattice` class defined in the module :mod:`~tenpy.models.lattice`, for example ``"Chain", "Square", "Honeycomb", ...``. Returns ------- LatticeClass : :class:`Lattice` The lattice class (type, not instance) specified by `lattice_name`. """ LatticeClass = globals()[lattice_name] assert issubclass(LatticeClass, Lattice) return LatticeClass
Example #4
Source File: model_tmmd.py From opt-mmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def discriminator(self, image, y=None, reuse=False): if reuse: tf.get_variable_scope().reuse_variables() s = self.output_size if np.mod(s, 16) == 0: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = lrelu(self.d_bn2(conv2d(h1, self.df_dim*4, name='d_h2_conv'))) h3 = lrelu(self.d_bn3(conv2d(h2, self.df_dim*8, name='d_h3_conv'))) h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h3_lin') return tf.nn.sigmoid(h4), h4 else: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = linear(tf.reshape(h1, [self.batch_size, -1]), 1, 'd_h2_lin') if not self.config.use_kernel: return tf.nn.sigmoid(h2), h2 else: return tf.nn.sigmoid(h2), h2, h1, h0
Example #5
Source File: model_mmd_fm.py From opt-mmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def discriminator(self, image, y=None, reuse=False): if reuse: tf.get_variable_scope().reuse_variables() s = self.output_size if np.mod(s, 16) == 0: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = lrelu(self.d_bn2(conv2d(h1, self.df_dim*4, name='d_h2_conv'))) h3 = lrelu(self.d_bn3(conv2d(h2, self.df_dim*8, name='d_h3_conv'))) h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h3_lin') return tf.nn.sigmoid(h4), h4 else: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = linear(tf.reshape(h1, [self.batch_size, -1]), 1, 'd_h2_lin') if not self.config.use_kernel: return tf.nn.sigmoid(h2), h2 else: return tf.nn.sigmoid(h2), h2, h1, h0
Example #6
Source File: charges.py From tenpy with GNU General Public License v3.0 | 6 votes |
def save_hdf5(self, hdf5_saver, h5gr, subpath): """Export `self` into a HDF5 file. This method saves all the data it needs to reconstruct `self` with :meth:`from_hdf5`. It stores the :attr:`names` under the path ``"names"``, and :attr:`mod` as dataset ``"U1_ZN"``. Parameters ---------- hdf5_saver : :class:`~tenpy.tools.hdf5_io.Hdf5Saver` Instance of the saving engine. h5gr : :class`Group` HDF5 group which is supposed to represent `self`. subpath : str The `name` of `h5gr` with a ``'/'`` in the end. """ h5gr.attrs['num_charges'] = self._qnumber hdf5_saver.save(self._mod, subpath + "U1_ZN") hdf5_saver.save(self.names, subpath + "names")
Example #7
Source File: charges.py From tenpy with GNU General Public License v3.0 | 6 votes |
def drop(cls, chinfo, charge=None): """Remove a charge from a :class:`ChargeInfo`. Parameters ---------- chinfo : :class:`ChargeInfo` The ChargeInfo from where to drop/remove a charge. charge : int | str Number or `name` of the charge (within `chinfo`) which is to be dropped. ``None`` means dropping all charges. Returns ------- chinfo : :class:`ChargeInfo` ChargeInfo where the specified charge is dropped. """ if charge is None: return cls() # trivial charge if isinstance(charge, str): charge = chinfo.names.index(charge) names = list(chinfo.names) names.pop(charge) return cls(np.delete(chinfo.mod, charge), names)
Example #8
Source File: charges.py From tenpy with GNU General Public License v3.0 | 6 votes |
def change(cls, chinfo, charge, new_qmod, new_name=''): """Change the `qmod` of a given charge. Parameters ---------- chinfo : :class:`ChargeInfo` The ChargeInfo for which `qmod` of `charge` should be changed. new_qmod : int The new `qmod` to be set. new_name : str The new name of the charge. Returns ------- chinfo : :class:`ChargeInfo` ChargeInfo where `qmod` of the specified charge was changed. """ if isinstance(charge, str): charge = chinfo.names.index(charge) names = list(chinfo.names) names[charge] = new_name mod = chinfo.mod.copy() mod[charge] = new_qmod return cls(mod, names)
Example #9
Source File: model_mmd.py From opt-mmd with BSD 3-Clause "New" or "Revised" License | 6 votes |
def discriminator(self, image, y=None, reuse=False): if reuse: tf.get_variable_scope().reuse_variables() s = self.output_size if np.mod(s, 16) == 0: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = lrelu(self.d_bn2(conv2d(h1, self.df_dim*4, name='d_h2_conv'))) h3 = lrelu(self.d_bn3(conv2d(h2, self.df_dim*8, name='d_h3_conv'))) h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h3_lin') return tf.nn.sigmoid(h4), h4 else: h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv')) h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv'))) h2 = linear(tf.reshape(h1, [self.batch_size, -1]), 1, 'd_h2_lin') if not self.config.use_kernel: return tf.nn.sigmoid(h2), h2 else: return tf.nn.sigmoid(h2), h2, h1, h0
Example #10
Source File: charges.py From tenpy with GNU General Public License v3.0 | 6 votes |
def make_valid(self, charges=None): """Take charges modulo self.mod. Parameters ---------- charges : array_like or None 1D or 2D array of charges, last dimension `self.qnumber` None defaults to trivial charges ``np.zeros(qnumber, dtype=QTYPE)``. Returns ------- charges : A copy of `charges` taken modulo `mod`, but with ``x % 1 := x`` """ if charges is None: return np.zeros((self.qnumber, ), dtype=QTYPE) charges = np.asarray(charges, dtype=QTYPE) charges[..., self._mask] = np.mod(charges[..., self._mask], self._mod_masked) return charges
Example #11
Source File: CausalGAN.py From CausalGAN with MIT License | 6 votes |
def train_step(self,sess,counter): ''' This is a generic function that will be called by the Trainer class once per iteration. The simplest body for this part would be simply "sess.run(self.train_op)". But you may have more complications. Running self.summary_op is handeled by Trainer.Supervisor and doesn't need to be addressed here Only counters, not epochs are explicitly kept track of ''' ###You can wait until counter>N to do stuff for example: if self.config.pretrain_LabelerR and counter < self.config.pretrain_LabelerR_no_of_iters: sess.run(self.d_label_optim) else: if np.mod(counter, 3) == 0: sess.run(self.g_optim) sess.run([self.train_op,self.k_t_update,self.inc_step])#all ops else: sess.run([self.g_optim, self.k_t_update ,self.inc_step]) sess.run(self.g_optim)
Example #12
Source File: kitti_data.py From lingvo with Apache License 2.0 | 6 votes |
def BBox3DToKITTIObject(bbox3d, velo_to_cam_transform): """Convert one bbox3d into KITTI's location, dimension, and rotation_y.""" x, y, z, length, width, height, rot = bbox3d # Avoid transforming objects with invalid boxes. See _KITTIObjectHas3DInfo. if width == -1 or length == -1 or height == -1: return [-1000, -1000, -1000], [-1, -1, -1], -10 # Convert our velodyne bbox rotation back to camera. Reverse the direction and # rotate by np.pi/2. See http://www.cvlibs.net/datasets/kitti/setup.php. rotation_y = rot + np.pi / 2. rotation_y = -rotation_y rotation_y = np.mod(rotation_y, 2 * np.pi) rotation_y = np.where(rotation_y >= np.pi, rotation_y - 2 * np.pi, rotation_y) # Reposition z so that it is at the bottom of the object. if height > 0: z -= height / 2. camera_xyz = np.dot(velo_to_cam_transform, np.asarray([x, y, z, 1.])) location = camera_xyz.tolist()[:3] dimensions = height, width, length return location, dimensions, rotation_y
Example #13
Source File: basic_observables.py From pytim with GNU General Public License v3.0 | 6 votes |
def compute(self, inp): try: pos = inp.atoms.positions pos = pos.flatten() except AttributeError: try: pos = inp.flatten() except AttributeError: raise ValueError('must pass an atom group or a ndarray') n = pos.shape[0] if np.mod(n, 9) > 0: # 3 atoms x 3 coordinates raise ValueError('number of atoms in group not a multiple of 3') n = n // 3 pos = pos.reshape(n, 3, 3) if self.QR is True: return np.asarray([np.linalg.qr(A)[0] for A in pos]) else: return np.asarray([self._modified_GS(A) for A in pos])
Example #14
Source File: Hurst.py From Hurst-exponent-R-S-analysis- with MIT License | 5 votes |
def hurst(ts): ts = list(ts) N = len(ts) if N < 20: raise ValueError("Time series is too short! input series ought to have at least 20 samples!") max_k = int(np.floor(N/2)) R_S_dict = [] for k in range(10,max_k+1): R,S = 0,0 # split ts into subsets subset_list = [ts[i:i+k] for i in range(0,N,k)] if np.mod(N,k)>0: subset_list.pop() #tail = subset_list.pop() #subset_list[-1].extend(tail) # calc mean of every subset mean_list=[np.mean(x) for x in subset_list] for i in range(len(subset_list)): cumsum_list = pd.Series(subset_list[i]-mean_list[i]).cumsum() R += max(cumsum_list)-min(cumsum_list) S += np.std(subset_list[i]) R_S_dict.append({"R":R/len(subset_list),"S":S/len(subset_list),"n":k}) log_R_S = [] log_n = [] print(R_S_dict) for i in range(len(R_S_dict)): R_S = (R_S_dict[i]["R"]+np.spacing(1)) / (R_S_dict[i]["S"]+np.spacing(1)) log_R_S.append(np.log(R_S)) log_n.append(np.log(R_S_dict[i]["n"])) Hurst_exponent = np.polyfit(log_n,log_R_S,1)[0] return Hurst_exponent
Example #15
Source File: charges.py From tenpy with GNU General Public License v3.0 | 5 votes |
def __setstate__(self, state): """Allow to pickle and copy.""" qnumber, mod, names = state self._mod = mod self._qnumber = mod.shape[0] assert qnumber == self._qnumber self._mask = np.not_equal(mod, 1) # where we need to take modulo in :meth:`make_valid` self._mod_masked = mod[self._mask].copy() # only where mod != 1 self.names = names
Example #16
Source File: charges.py From tenpy with GNU General Public License v3.0 | 5 votes |
def __eq__(self, other): """Compare self.mod and self.names for equality, ignore missing names.""" if self is other: return True if not np.all(self.mod == other.mod): return False for l, r in zip(self.names, other.names): if r != l and l != '' and r != '': return False return True
Example #17
Source File: charges.py From tenpy with GNU General Public License v3.0 | 5 votes |
def from_change_charge(cls, leg, charge, new_qmod, new_name='', chargeinfo=None): """Remove a charge from a LegCharge. Parameters ---------- leg : :class:`LegCharge` The leg from which to drop/remove a charge. charge : int | str Number or `name` of the charge (within `chinfo`) for which `mod` is to be changed. new_qmod : int The new `mod` to be set for `charge` in the :class:`ChargeInfo`. new_name : str The new name for `charge`. chargeinfo : :class:`ChargeInfo` The ChargeInfo with `charge` changed; create new if ``None``. Returns ------- leg : :class:`LegCharge` A LegCharge with the specified charge changed. Is neither sorted nor bunched! """ chinfo = ChargeInfo.change(leg.chinfo, charge, new_qmod, new_name) if chargeinfo is not None: assert chinfo == chargeinfo chinfo = chargeinfo charges = chinfo.make_valid(leg.charges) return cls.from_qind(chinfo, leg.slices, charges, leg.qconj)
Example #18
Source File: math.py From formulas with European Union Public License 1.1 | 5 votes |
def xmod(x, y): return y == 0 and Error.errors['#DIV/0!'] or np.mod(x, y)
Example #19
Source File: prepare_test.py From SRCNN with MIT License | 5 votes |
def modcrop(image, scale=3): if image.shape[2] == 1: size = image.shape size -= np.mod(size, scale) image = image[0:size[0], 0:size[1]] else: size = image.shape[0:2] size -= np.mod(size, scale) image = image[0:size[0], 0:size[1], 0] return image
Example #20
Source File: prepare_train.py From SRCNN with MIT License | 5 votes |
def modcrop(image, scale=3): if image.shape[2] == 1: size = image.shape size -= np.mod(size, scale) image = image[0:size[0], 0:size[1]] else: size = image.shape[0:2] size -= np.mod(size, scale) image = image[0:size[0], 0:size[1], 0] return image # Load and preprocess the training images.
Example #21
Source File: breakdown_metric.py From lingvo with Apache License 2.0 | 5 votes |
def _CalculateRotation(self, bboxes): """Calculate rotation angle mod between (0, 2 * pi) for each box. Args: bboxes: [N, 7] np.float of N bounding boxes. See details above. Returns: np.array [N] of rotation angles in radians. """ if not bboxes.size: return np.empty_like(bboxes) p = self.params # Although groundtruth is constrained to be in [-pi, pi], predictions are # unbounded. We map all predictions to their equivalent value in [-pi, pi]. rotations = np.copy(bboxes[:, -1]) rotations += np.pi rotations = np.mod(rotations, 2.0 * np.pi) rotations -= np.pi # Now we remove ambiguity in 180 degree rotations as measured by our IOU # calculations by mapping everything to [0, pi] range. rotations = np.where(rotations > 0.0, rotations, rotations + np.pi) # Floating numerical issues can surface occasionally particularly within # subsequent binning. The clipping makes these operations reliable. epsilon = 1e-5 rotations = np.clip(rotations, epsilon, p.metadata.MaximumRotation() - epsilon) return rotations
Example #22
Source File: charges.py From tenpy with GNU General Public License v3.0 | 5 votes |
def __repr__(self): """Full string representation.""" return "ChargeInfo({0!s}, {1!s})".format(list(self.mod), self.names)
Example #23
Source File: utils.py From yatsm with MIT License | 5 votes |
def iter_records(records, warn_on_empty=False, yield_filename=False): """ Iterates over records, returning result NumPy array Args: records (list): List containing filenames of results warn_on_empty (bool, optional): Log warning if result contained no result records (default: False) yield_filename (bool, optional): Yield the filename and the record Yields: np.ndarray or tuple: Result saved in record and the filename, if desired """ n_records = len(records) for _i, r in enumerate(records): # Verbose progress if np.mod(_i, 100) == 0: logger.debug('{0:.1f}%'.format(_i / n_records * 100)) # Open output try: rec = np.load(r)['record'] except (ValueError, AssertionError, IOError) as e: logger.warning('Error reading a result file (may be corrupted) ' '({}): {}'.format(r, str(e))) continue if rec.shape[0] == 0: # No values in this file if warn_on_empty: logger.warning('Could not find results in {f}'.format(f=r)) continue if yield_filename: yield rec, r else: yield rec # MISC UTILITIES
Example #24
Source File: bh.py From dustmaps with GNU General Public License v2.0 | 5 votes |
def _lb2RN_mid(self, l, b): R = (np.abs(b) - 10.) / 0.6 N = (np.mod(l, 360.) + 0.15) / 0.3 - 1 return np.round(R).astype('i4'), np.round(N).astype('i4')
Example #25
Source File: ccdc.py From yatsm with MIT License | 5 votes |
def _get_dynamic_rmse(self): """ Return the dynamic RMSE for each model Dynamic RMSE refers to the Root Mean Squared Error calculated using `self.min_obs` number of observations closest in day of year to the observation `self.consecutive` steps into the future. Goal is to reduce false-positives during seasonal transitions (high variance in the signal) while decreasing omission during stable times of year. Returns: numpy.ndarray: dynamic RMSE of each tested model """ # Indices of closest observations based on DOY i_doy = np.argsort( np.mod(self.dates[self.start:self.here] - self.dates[self.here + self.consecutive], self.ndays))[:self.min_obs] _rmse = np.zeros(len(self.test_indices), np.float32) _X = self.X.take(i_doy, axis=0) for i_b, b in enumerate(self.test_indices): m = self.models[b] _rmse[i_b] = rmse(self.Y[b, :].take(i_doy), m.predict(_X)) return _rmse
Example #26
Source File: multiScaleEntropy.py From HRV with MIT License | 5 votes |
def multiScaleEntropy(timeSeries, scales, r, m): '''MultiScaleEntropy - algorithm to calculate multiscale entropy (MSE) for complex time series. Introduced by Costa, et al (2002) Inputs Arguments: - timeSeries: [list] of time series data - scales : [list] of scales for MSE calculation - r : [float] tolerance (typically 0.2*std(time series)) - m : [int] embedding dimension (typically 2) Ouputs Arguments: - MSE : [array] of sample entropy at scales --> size [1 length(scales)] ''' N = len(timeSeries) MSE = [] for s in scales: if s > N: print('Scale must not exceed length of the time series') else: #"course-graining" process cuts = np.reshape(timeSeries[:(N - int(np.mod(N, s)))], (int(np.floor(N/s)), int(s))) coarseGrainedSeries = np.mean(cuts, 1) MSE.append(sampEn(coarseGrainedSeries, m, r)) return MSE
Example #27
Source File: test_core.py From recruit with Apache License 2.0 | 5 votes |
def test_mod(self): # Tests mod (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d assert_equal(mod(x, y), mod(xm, ym)) test = mod(ym, xm) assert_equal(test, np.mod(ym, xm)) assert_equal(test.mask, mask_or(xm.mask, ym.mask)) test = mod(xm, ym) assert_equal(test, np.mod(xm, ym)) assert_equal(test.mask, mask_or(mask_or(xm.mask, ym.mask), (ym == 0)))
Example #28
Source File: test_ufunc.py From recruit with Apache License 2.0 | 5 votes |
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, np.greater, np.greater_equal, np.less, np.less_equal, np.equal, np.not_equal] a = np.array('1') b = 1 c = np.array([1., 2.]) for f in binary_funcs: assert_raises(TypeError, f, a, b) assert_raises(TypeError, f, c, a)
Example #29
Source File: test_ephys_trials.py From ibllib with MIT License | 5 votes |
def test_wheel_trace_from_sync(self): pos_ = - np.array([-1, 0, -1, -2, -1, -2]) * (np.pi / ephys_fpga.WHEEL_TICKS) ta = np.array([1, 2, 3, 4, 5, 6]) tb = np.array([0.5, 3.2, 3.3, 3.4, 5.25, 5.5]) pa = (np.mod(np.arange(6), 2) - 0.5) * 2 pb = (np.mod(np.arange(6) + 1, 2) - .5) * 2 t, pos = ephys_fpga._rotary_encoder_positions_from_fronts(ta, pa, tb, pb, coding='x2') self.assertTrue(np.all(np.isclose(pos_, pos))) pos_ = - np.array([-1, 0, -1, 0, -1, -2]) * (np.pi / ephys_fpga.WHEEL_TICKS) tb = np.array([0.5, 3.2, 3.4, 5.25]) pb = (np.mod(np.arange(4) + 1, 2) - .5) * 2 t, pos = ephys_fpga._rotary_encoder_positions_from_fronts(ta, pa, tb, pb, coding='x2') self.assertTrue(np.all(np.isclose(pos_, pos)))
Example #30
Source File: frequencies.py From recruit with Apache License 2.0 | 5 votes |
def _is_business_daily(self): # quick check: cannot be business daily if self.day_deltas != [1, 3]: return False # probably business daily, but need to confirm first_weekday = self.index[0].weekday() shifts = np.diff(self.index.asi8) shifts = np.floor_divide(shifts, _ONE_DAY) weekdays = np.mod(first_weekday + np.cumsum(shifts), 7) return np.all(((weekdays == 0) & (shifts == 3)) | ((weekdays > 0) & (weekdays <= 4) & (shifts == 1)))