Python itertools.combinations_with_replacement() Examples

The following are 30 code examples for showing how to use itertools.combinations_with_replacement(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module itertools , or try the search function .

Example 1
Project: buzzard   Author: airware   File: test_footprint_precision.py    License: Apache License 2.0 6 votes vote down vote up
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 2
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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
Project: qmpy   Author: wolverton-research-group   File: pdf.py    License: MIT License 6 votes vote down vote up
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 5
Project: pex   Author: pantsbuild   File: temp_dir.py    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: deepWordBug   Author: QData   File: temp_dir.py    License: Apache License 2.0 6 votes vote down vote up
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 7
Project: picklable-itertools   Author: mila-iqia   File: __init__.py    License: MIT License 6 votes vote down vote up
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 8
Project: pipenv   Author: pypa   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 9
Project: momi2   Author: popgenmethods   File: sfs.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 10
Project: Building-Recommendation-Systems-with-Python   Author: PacktPublishing   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 11
Project: Building-Recommendation-Systems-with-Python   Author: PacktPublishing   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 12
Project: scylla   Author: acaceres2176   File: temp_dir.py    License: Apache License 2.0 6 votes vote down vote up
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 13
Project: learn_python3_spider   Author: wistbean   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 14
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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
Project: Weapon-Detection-And-Classification   Author: ivaibhavkr   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 16
Project: everest   Author: rodluger   File: basecamp.py    License: MIT License 6 votes vote down vote up
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 17
Project: rules_pip   Author: ali5h   File: temp_dir.py    License: MIT License 6 votes vote down vote up
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 18
Project: hwrt   Author: MartinThoma   File: features.py    License: MIT License 6 votes vote down vote up
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 19
Project: PyChemia   Author: MaterialsDiscovery   File: analysis.py    License: MIT License 6 votes vote down vote up
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 20
Project: PyChemia   Author: MaterialsDiscovery   File: analysis.py    License: MIT License 6 votes vote down vote up
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 21
Project: minian   Author: DeniseCaiLab   File: mappings.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 22
Project: scikit-multilearn   Author: scikit-multilearn   File: measures.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 23
Project: orbkit   Author: orbkit   File: ao_integrals.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 24
Project: 3DUnetCNN   Author: ellisdg   File: augment.py    License: MIT License 6 votes vote down vote up
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 25
Project: lammps_interface   Author: peteboyd   File: ForceFields.py    License: MIT License 6 votes vote down vote up
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 26
Project: 3D-CNNs-for-Liver-Classification   Author: wcfzl   File: augment.py    License: Apache License 2.0 6 votes vote down vote up
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 27
Project: abu   Author: bbfamily   File: ABuFixes.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 28
Project: abu   Author: bbfamily   File: c2.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 29
Project: fullrmc   Author: bachiraoun   File: StructureFactorConstraints.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __set_weighting_scheme(self):
        if self.engine is not None:
            self.__elementsPairs   = sorted(itertools.combinations_with_replacement(self.engine.elements,2))
            #elementsWeight        = dict([(el,float(get_element_property(el,self.__weighting))) for el in self.engine.elements])
            #self._elementsWeight  = dict([(el,self.__atomsWeight.get(el, float(get_element_property(el,self.__weighting)))) for el in self.engine.elements])
            self._elementsWeight   = get_real_elements_weight(elements=self.engine.elements, weightsDict=self.__atomsWeight, weighting=self.__weighting)
            self.__weightingScheme = get_normalized_weighting(numbers=self.engine.numberOfAtomsPerElement, weights=self._elementsWeight)
            for k in self.__weightingScheme:
                self.__weightingScheme[k] = FLOAT_TYPE(self.__weightingScheme[k])
        else:
            self.__elementsPairs   = None
            self.__weightingScheme = None
        # dump to repository
        self._dump_to_repository({'_StructureFactorConstraint__elementsPairs'  : self.__elementsPairs,
                                  '_StructureFactorConstraint__weightingScheme': self.__weightingScheme}) 
Example 30
Project: fullrmc   Author: bachiraoun   File: PairDistributionConstraints.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def listen(self, message, argument=None):
        """
        Listens to any message sent from the Broadcaster.

        :Parameters:
            #. message (object): Any python object to send to constraint's
               listen method.
            #. argument (object): Any type of argument to pass to the listeners.
        """
        if message in ("engine set","update pdb","update molecules indexes","update elements indexes","update names indexes"):
            if self.engine is not None:
                self.__elementsPairs   = sorted(itertools.combinations_with_replacement(self.engine.elements,2))
                self._elementsWeight   = get_real_elements_weight(elements=self.engine.elements, weightsDict=self.__atomsWeight, weighting=self.__weighting)
                self.__weightingScheme = get_normalized_weighting(numbers=self.engine.numberOfAtomsPerElement, weights=self._elementsWeight)
                for k in self.__weightingScheme:
                    self.__weightingScheme[k] = FLOAT_TYPE(self.__weightingScheme[k])
            else:
                self.__elementsPairs   = None
                self._elementsWeight   = None
                self.__weightingScheme = None
            # dump to repository
            self._dump_to_repository({'_PairDistributionConstraint__elementsPairs'  : self.__elementsPairs,
                                      '_PairDistributionConstraint__weightingScheme': self.__weightingScheme,
                                      '_elementsWeight': self._elementsWeight})
            self.reset_constraint() # ADDED 2017-JAN-08
        elif message in("update boundary conditions",):
            self.reset_constraint()