當前位置: 首頁>>代碼示例>>Python>>正文


Python itertools.combinations_with_replacement方法代碼示例

本文整理匯總了Python中itertools.combinations_with_replacement方法的典型用法代碼示例。如果您正苦於以下問題:Python itertools.combinations_with_replacement方法的具體用法?Python itertools.combinations_with_replacement怎麽用?Python itertools.combinations_with_replacement使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在itertools的用法示例。


在下文中一共展示了itertools.combinations_with_replacement方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_same_grid_and_move

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:airware,項目名稱:buzzard,代碼行數:23,代碼來源:test_footprint_precision.py

示例2: _generate_names

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:24,代碼來源:temp_dir.py

示例3: __init__

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 ]) 
開發者ID:wolverton-research-group,項目名稱:qmpy,代碼行數:21,代碼來源:pdf.py

示例4: _generate_names

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:25,代碼來源:temp_dir.py

示例5: test_combinations_with_replacement

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:mila-iqia,項目名稱:picklable-itertools,代碼行數:21,代碼來源:__init__.py

示例6: _get_subsample_counts

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:popgenmethods,項目名稱:momi2,代碼行數:25,代碼來源:sfs.py

示例7: X

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:rodluger,項目名稱:everest,代碼行數:18,代碼來源:basecamp.py

示例8: __call__

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:MartinThoma,項目名稱:hwrt,代碼行數:27,代碼來源:features.py

示例9: all_distances

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:MaterialsDiscovery,項目名稱:PyChemia,代碼行數:20,代碼來源:analysis.py

示例10: all_distances_by_species

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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 
開發者ID:MaterialsDiscovery,項目名稱:PyChemia,代碼行數:26,代碼來源:analysis.py

示例11: compute_correlations

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:DeniseCaiLab,項目名稱:minian,代碼行數:27,代碼來源:mappings.py

示例12: get_combination_wise_output_matrix

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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]) 
開發者ID:scikit-multilearn,項目名稱:scikit-multilearn,代碼行數:20,代碼來源:measures.py

示例13: _get_order

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:orbkit,項目名稱:orbkit,代碼行數:20,代碼來源:ao_integrals.py

示例14: generate_permutation_keys

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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))) 
開發者ID:ellisdg,項目名稱:3DUnetCNN,代碼行數:19,代碼來源:augment.py

示例15: van_der_waals_pairs

# 需要導入模塊: import itertools [as 別名]
# 或者: from itertools import combinations_with_replacement [as 別名]
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) 
開發者ID:peteboyd,項目名稱:lammps_interface,代碼行數:23,代碼來源:ForceFields.py


注:本文中的itertools.combinations_with_replacement方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。