Python itertools.combinations_with_replacement() Examples
The following are 30
code examples of itertools.combinations_with_replacement().
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
itertools
, or try the search function
.
Example #1
Source File: temp_dir.py From Weapon-Detection-And-Classification with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #2
Source File: temp_dir.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #3
Source File: temp_dir.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #4
Source File: measures.py From scikit-multilearn with BSD 2-Clause "Simplified" License | 6 votes |
def get_combination_wise_output_matrix(y, order): """Returns label combinations of a given order that are assigned to each row Parameters: ----------- y : output matrix or array of arrays (n_samples, n_labels) the binary-indicator label assignment per sample representation of the output space order : int, >= 1 the order of label relationship to take into account when balancing sample distribution across labels Returns ------- combinations_per_row : List[Set[Tuple[int]]] list of combination assignments per row """ return np.array([set(tuple(combination) for combination in it.combinations_with_replacement(get_indicator_representation(row), order)) for row in y])
Example #5
Source File: ao_integrals.py From orbkit with GNU Lesser General Public License v3.0 | 6 votes |
def _get_order(self, i): '''Returns indices to transform libcint order to orbkit order for given shell.''' l = self.basis.bas[i][1] if l == 0: return (0,) if self.cartesian: order_orbkit = self.qc.ao_spec.get_lxlylz()[self.qc.ao_spec.get_assign_lxlylz_to_cont()==i,:] order_libcint = [] for item in combinations_with_replacement('xyz', l): order_libcint.append([item.count('x'), item.count('y'), item.count('z')]) order_libcint = numpy.array(order_libcint) else: order_orbkit = numpy.array(self.qc.ao_spec.get_lm())[self.qc.ao_spec.get_assign_lm_to_cont()==i,1] if l == 1: order_libcint = numpy.array([1,-1,0]) else: order_libcint = numpy.array(range(-l,l+1)) return match_order(order_libcint, order_orbkit)
Example #6
Source File: augment.py From 3DUnetCNN with MIT License | 6 votes |
def generate_permutation_keys(): """ This function returns a set of "keys" that represent the 48 unique rotations & reflections of a 3D matrix. Each item of the set is a tuple: ((rotate_y, rotate_z), flip_x, flip_y, flip_z, transpose) As an example, ((0, 1), 0, 1, 0, 1) represents a permutation in which the data is rotated 90 degrees around the z-axis, then reversed on the y-axis, and then transposed. 48 unique rotations & reflections: https://en.wikipedia.org/wiki/Octahedral_symmetry#The_isometries_of_the_cube """ return set(itertools.product( itertools.combinations_with_replacement(range(2), 2), range(2), range(2), range(2), range(2)))
Example #7
Source File: pdf.py From qmpy with MIT License | 6 votes |
def __init__(self, structure, limit=10): elements = structure.comp.keys() pairs = itertools.combinations_with_replacement(elements, r=2) self.pairs = [ self.get_pair(pair) for pair in pairs ] self.distances = dict((p, []) for p in self.pairs) self.weights = dict((p, []) for p in self.pairs) structure = structure.copy() # `get_symmetry_dataset` cannot handle the reduced output? structure.reduce() structure.symmetrize() self.structure = structure self.cell = self.structure.cell self.uniq = self.structure.uniq_sites self.sites = self.structure.sites self.limit = limit self.limit2 = limit**2 lp = structure.find_lattice_points_within_distance(limit) self.lattice_points = np.array([ np.dot(p, self.cell) for p in lp ])
Example #8
Source File: augment.py From 3D-CNNs-for-Liver-Classification with Apache License 2.0 | 6 votes |
def generate_permutation_keys(): """ This function returns a set of "keys" that represent the 48 unique rotations & reflections of a 3D matrix. Each item of the set is a tuple: ((rotate_y, rotate_z), flip_x, flip_y, flip_z, transpose) As an example, ((0, 1), 0, 1, 0, 1) represents a permutation in which the data is rotated 90 degrees around the z-axis, then reversed on the y-axis, and then transposed. 48 unique rotations & reflections: https://en.wikipedia.org/wiki/Octahedral_symmetry#The_isometries_of_the_cube """ return set(itertools.product( itertools.combinations_with_replacement(range(2), 2), range(2), range(2), range(2), range(2)))
Example #9
Source File: test_footprint_precision.py From buzzard with Apache License 2.0 | 6 votes |
def test_same_grid_and_move(fp, env): ofp = fp if env < ofp._significant_min + 1: pytest.skip() for factx, facty in itertools.combinations_with_replacement([-1, 0, +1], 2): tl = ofp.tl % ofp.pxsize + 1e9 // ofp.pxsize * ofp.pxsize * [factx, facty] fp = ofp.move(tl) if env < fp._significant_min: continue eps = np.abs(np.r_[fp.coords, ofp.coords]).max() * 10 ** -buzz.env.significant for factx, facty in itertools.combinations_with_replacement([-1, 0, +1], 2): fact = np.asarray([factx, facty]) fp = ofp.move(tl + eps * LESS_ERROR * fact) assert ofp.same_grid(fp) if (fact != 0).any(): fp = ofp.move(tl + eps * MORE_ERROR * fact) assert not ofp.same_grid(fp)
Example #10
Source File: ABuFixes.py From abu with GNU General Public License v3.0 | 6 votes |
def combinations_with_replacement(iterable, r): # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices)
Example #11
Source File: c2.py From abu with GNU General Public License v3.0 | 6 votes |
def sample_241_1(): """ 2.4.1_1 itertools的使用 :return: """ items = [1, 2, 3] for item in itertools.permutations(items): print(item) for item in itertools.combinations(items, 2): print(item) for item in itertools.combinations_with_replacement(items, 2): print(item) ab = ['a', 'b'] cd = ['c', 'd'] # 针对ab,cd两个集合进行排列组合 for item in itertools.product(ab, cd): print(item) # 两年的TSLA收盘数据 to list
Example #12
Source File: ForceFields.py From lammps_interface with MIT License | 6 votes |
def van_der_waals_pairs(self): atom_types = self.unique_atom_types.keys() for type1, type2 in itertools.combinations_with_replacement(atom_types, 2): atm1 = self.unique_atom_types[type1] atm2 = self.unique_atom_types[type2] print(str(re.findall(r'^[a-zA-Z]*',atm1.force_field_type)[0])) print(str(re.findall(r'^[a-zA-Z]*',atm2.force_field_type)[0])) # if we are using non-UFF atom types, need to splice off the end descriptors (first non alphabetic char) eps1 = UFF_DATA_nonbonded[re.findall(r'^[a-zA-Z]*',atm1.force_field_type)[0]][3] eps2 = UFF_DATA_nonbonded[re.findall(r'^[a-zA-Z]*',atm2.force_field_type)[0]][3] # radius --> sigma = radius*2**(-1/6) sig1 = UFF_DATA_nonbonded[re.findall(r'^[a-zA-Z]*',atm1.force_field_type)[0]][2]*(2**(-1./6.)) sig2 = UFF_DATA_nonbonded[re.findall(r'^[a-zA-Z]*',atm2.force_field_type)[0]][2]*(2**(-1./6.)) # l-b mixing eps = math.sqrt(eps1*eps2) sig = (sig1 + sig2) / 2. self.unique_pair_types[(type1, type2)] = (eps, sig)
Example #13
Source File: temp_dir.py From pex with Apache License 2.0 | 6 votes |
def _generate_names(cls, name): # type: (str) -> Iterator[str] """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #14
Source File: temp_dir.py From deepWordBug with Apache License 2.0 | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #15
Source File: __init__.py From picklable-itertools with MIT License | 6 votes |
def test_combinations_with_replacement(): yield (verify_same, combinations_with_replacement, itertools.combinations_with_replacement, None, _identity) yield (verify_same, combinations_with_replacement, itertools.combinations_with_replacement, None, _identity, []) yield (verify_same, combinations_with_replacement, itertools.combinations_with_replacement, None) yield (verify_same, combinations_with_replacement, itertools.combinations_with_replacement, None, [5, 4, 3, 2, 1], 2) yield (verify_pickle, combinations_with_replacement, itertools.combinations_with_replacement, 15, 3, [5, 4, 3, 2, 1], 2) yield (verify_pickle, combinations_with_replacement, itertools.combinations_with_replacement, 15, 0, [5, 4, 3, 2, 1], 2)
Example #16
Source File: temp_dir.py From pipenv with MIT License | 6 votes |
def _generate_names(cls, name): # type: (str) -> Iterator[str] """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #17
Source File: sfs.py From momi2 with GNU General Public License v3.0 | 6 votes |
def _get_subsample_counts(configs, n): subconfigs, weights = [], [] for pop_comb in it.combinations_with_replacement(configs.sampled_pops, n): subsample_n = co.Counter(pop_comb) subsample_n = np.array([subsample_n[pop] for pop in configs.sampled_pops], dtype=int) if np.any(subsample_n > configs.sampled_n): continue for sfs_entry in it.product(*(range(sub_n + 1) for sub_n in subsample_n)): sfs_entry = np.array(sfs_entry, dtype=int) if np.all(sfs_entry == 0) or np.all(sfs_entry == subsample_n): # monomorphic continue sfs_entry = np.transpose([subsample_n - sfs_entry, sfs_entry]) cnt_vec = configs.subsample_probs(sfs_entry) if not np.all(cnt_vec == 0): subconfigs.append(sfs_entry) weights.append(cnt_vec) return np.array(subconfigs), np.array(weights)
Example #18
Source File: temp_dir.py From Building-Recommendation-Systems-with-Python with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #19
Source File: temp_dir.py From Building-Recommendation-Systems-with-Python with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #20
Source File: temp_dir.py From scylla with Apache License 2.0 | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #21
Source File: analysis.py From PyChemia with MIT License | 6 votes |
def all_distances_by_species(self): all_distances = self.all_distances() ret = OrderedDict() atom_numbers = atomic_number(self.structure.species) a = list(itertools.combinations_with_replacement(atom_numbers, 2)) keys = sorted([tuple(sorted(list(x))) for x in a]) for key in keys: ret[key] = [] for ipair in all_distances: key = tuple(sorted(atomic_number([self.structure.symbols[ipair[0]], self.structure.symbols[ipair[1]]]))) if self.structure.is_periodic: ret[key] = np.concatenate((ret[key], all_distances[ipair]['distance'])) else: ret[key].append(all_distances[ipair]) # Sorting arrays for key in ret: ret[key].sort() ret[key] = np.array(ret[key]) return ret
Example #22
Source File: temp_dir.py From learn_python3_spider with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #23
Source File: analysis.py From PyChemia with MIT License | 6 votes |
def all_distances(self): if self._all_distances is None: ret = {} if not self.structure.is_periodic: dist_matrix = self.structure.distance_matrix() for i, j in itertools.combinations_with_replacement(range(self.structure.natom), 2): pair = (i, j) if self.structure.is_periodic: ret[pair] = self.structure.lattice.distances_in_sphere(self.structure.reduced[i], self.structure.reduced[j], radius=self.radius) else: ret[pair] = dist_matrix[i, j] self._all_distances = ret return self._all_distances
Example #24
Source File: temp_dir.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def _generate_names(cls, name): """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #25
Source File: features.py From hwrt with MIT License | 6 votes |
def __call__(self, hwr_obj): super(self.__class__, self).__call__(hwr_obj) pointlist = hwr_obj.get_pointlist() polygonal_chains = [] # Make sure the dimension is correct for i in range(self.strokes): if i < len(pointlist): polygonal_chains.append(geometry.PolygonalChain(pointlist[i])) else: polygonal_chains.append(geometry.PolygonalChain([])) x = [] for chainA, chainB in combinations_wr(polygonal_chains, 2): if chainA == chainB: x.append(chainA.count_selfintersections()) else: x.append(chainA.count_intersections(chainB)) assert self.get_dimension() == len(x), ( "Dimension of %s should be %i, but was %i" % (str(self), self.get_dimension(), len(x)) ) return x
Example #26
Source File: temp_dir.py From rules_pip with MIT License | 6 votes |
def _generate_names(cls, name): # type: (str) -> Iterator[str] """Generates a series of temporary names. The algorithm replaces the leading characters in the name with ones that are valid filesystem characters, but are not valid package names (for both Python and pip definitions of package). """ for i in range(1, len(name)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i - 1): new_name = '~' + ''.join(candidate) + name[i:] if new_name != name: yield new_name # If we make it this far, we will have to make a longer name for i in range(len(cls.LEADING_CHARS)): for candidate in itertools.combinations_with_replacement( cls.LEADING_CHARS, i): new_name = '~' + ''.join(candidate) + name if new_name != name: yield new_name
Example #27
Source File: basecamp.py From everest with MIT License | 6 votes |
def X(self, i, j=slice(None, None, None)): ''' Computes the design matrix at the given *PLD* order and the given indices. The columns are the *PLD* vectors for the target at the corresponding order, computed as the product of the fractional pixel flux of all sets of :py:obj:`n` pixels, where :py:obj:`n` is the *PLD* order. ''' X1 = self.fpix[j] / self.norm[j].reshape(-1, 1) X = np.product(list(multichoose(X1.T, i + 1)), axis=1).T if self.X1N is not None: return np.hstack([X, self.X1N[j] ** (i + 1)]) else: return X
Example #28
Source File: mappings.py From minian with GNU General Public License v3.0 | 6 votes |
def compute_correlations(temp_comp, along, across): segments = temp_comp.attrs['segments'] corr_list = [] for cur_anm in temp_comp['animal'].values: for comb in itt.combinations_with_replacement(segments, 2): dat_A = temp_comp.sel(animal=cur_anm, session_id=comb[0][0]) dat_A = dat_A.where( dat_A['segment_id'] == comb[0][1], drop=True).to_array().drop('segment_id').squeeze( 'variable', drop=True) dat_B = temp_comp.sel(animal=cur_anm, session_id=comb[1][0]) dat_B = dat_B.where( dat_B['segment_id'] == comb[1][1], drop=True).to_array().drop('segment_id').squeeze( 'variable', drop=True) if dat_A.size > 0 and dat_B.size > 0: print("computing correlation of {} with {} for animal {}". format(comb[0], comb[1], cur_anm)) cur_corr = corr2_coeff_xr(dat_A, dat_B, along, across) cur_corr.coords['session_id_A'] = comb[0][0] cur_corr.coords['session_id_B'] = comb[1][0] cur_corr.coords['segment_id_A'] = comb[0][1] cur_corr.coords['segment_id_B'] = comb[1][1] print("merging") return xr.merge(corr_list)
Example #29
Source File: metrics.py From sigsep-mus-eval with MIT License | 5 votes |
def _compute_reference_correlations(reference_sources, filters_len): """Compute the inner products between delayed versions of reference_sources reference is nsrc X nsamp X nchan. Returns * G, matrix : nsrc X nsrc X nchan X nchan X filters_len X filters_len * sf, reference spectra: nsrc X nchan X filters_len""" # reshape references as nsrc X nchan X nsampl (nsrc, nsampl, nchan) = reference_sources.shape reference_sources = np.moveaxis(reference_sources, (1), (2)) # zero padding and FFT of references reference_sources = _zeropad(reference_sources, filters_len - 1, axis=2) n_fft = int(2**np.ceil(np.log2(nsampl + filters_len - 1.))) sf = scipy.fftpack.fft(reference_sources, n=n_fft, axis=2) # compute intercorrelation between sources G = np.zeros((nsrc, nsrc, nchan, nchan, filters_len, filters_len)) for ((i, c1), (j, c2)) in itertools.combinations_with_replacement( itertools.product( list(range(nsrc)), list(range(nchan)) ), 2 ): ssf = sf[j, c2] * np.conj(sf[i, c1]) ssf = np.real(scipy.fftpack.ifft(ssf)) ss = toeplitz( np.hstack((ssf[0], ssf[-1:-filters_len:-1])), r=ssf[:filters_len] ) G[j, i, c2, c1] = ss G[i, j, c1, c2] = ss.T return G, sf
Example #30
Source File: test_tctc.py From teneto with GNU General Public License v3.0 | 5 votes |
def df_to_array(df, outshape): out = np.zeros(outshape) for _, r in df.iterrows(): ind = list( zip(*list(itertools.combinations_with_replacement(r['community'], 2)))) out[ind[0]+ind[1], ind[1]+ind[0], r['start']:r['end']] = 1 return out