def generateBucket(b): global player_switch_templates global templates #This will output the bth bucket of bimatrices. #Should be the case that 0 <= b < 50,808,240 player_one_template = np.array(templates[next(it.islice(it.combinations_with_replacement(range(10080), 2), b))[0]]) print "player_one_template is \n", player_one_template player_two_util_possibilities = [] #initiate empty. This should end up being a list of 36 elements player_two_template_num = next(it.islice(it.combinations_with_replacement(range(10080), 2),b))[1] print "player_two_template_num = ", player_two_template_num print "finding player_switch_templates that equal ", player_two_template_num, " ..." for i, x in enumerate(player_switch_templates): if x==player_two_template_num: player_two_util_possibilities.append(i) print "... finished. Found ", len(player_two_util_possibilities), " permutations that correspond to this player_two_template_num" print "player_two_util_possibilities = ", player_two_util_possibilities output = [] # initialize empty for i in range(len(player_two_util_possibilities)): print "i = ", i print "player_two_util_possibilities[i] = ", player_two_util_possibilities[i] slice_var = it.islice(it.permutations(range(1,10)), player_two_util_possibilities[i], None) print "slice_var = ", slice_var player_two_utils = list(next(slice_var, None)) print "player_two_utils = ", player_two_utils player_two_template = np.array(player_two_utils).reshape(3, 3) print "player_two_template = ", player_two_template print "appending: \n", np.array([player_one_template, player_two_template]), "\n" output.append(np.array([player_one_template, player_two_template])) return output
def test_operators_with_poly_input_keeping_zero(self, op, zero): if op.rev: # Testing binary reversed for p0, p1 in combinations_with_replacement(self.polynomials, 2): p0 = Poly(p0) p1 = Poly(p1, zero) result = getattr(p0, op.dname)(p1) assert isinstance(result, Poly) assert result.zero == 0 result = getattr(p1, op.dname)(p0) assert isinstance(result, Poly) assert result.zero is zero elif op.arity == 2: # Testing binary for p0, p1 in combinations_with_replacement(self.polynomials, 2): p0 = Poly(p0) p1 = Poly(p1, zero) result = op.func(p0, p1) assert isinstance(result, Poly) assert result.zero == 0 result = op.func(Poly(p1), p0) # Should keep assert isinstance(result, Poly) assert result.zero is zero else: # Testing unary for poly in self.polynomials: poly = Poly(poly, zero) result = op.func(poly) assert isinstance(result, Poly) assert result.zero is zero
def generate_spot_ratio_groups(self): """Return an iterator that returns the ratio groups. Each returned group is a list of ratios in the form of two-item tuples. """ for end in range(6, 31, 5): previous_end = end-5 # Plates where one species has all 25 spots covered are not # expected to be significant. So we exclude these from the # ratios. if end == 26: end = 25 # Get the ratios for this group. group = itertools.combinations_with_replacement(xrange(1,end), 2) group = list(group) if end > 6: # Remove the ratios of the previous groups from the current group. remove = itertools.combinations_with_replacement(xrange(1,previous_end), 2) setlyze.std.remove_items_from_list(group,remove) # Yield the ratios for this group. yield group # Lastly, yield all ratios (excluding the ones containing 25) all_ratios = list(itertools.combinations_with_replacement(xrange(1,25), 2)) yield all_ratios
def compute_distances(self): points_list = [[(p[0], p[1]) for p in persistence.points if p[2] == self.degree]\ for persistence in self.persistences.diagrams] ij_iterator = itertools.combinations_with_replacement(range(len(points_list)),2) if self.pool == None : similarities = itertools.imap(ScaleSpaceWrapper(float(self.kernel_scale)), itertools.combinations_with_replacement(points_list,2)) #distances = itertools.imap(average_pairing_distance, # itertools.combinations_with_replacement(points_list,2)) else : work_unit_size = max(1, (len(points_list) + 1) * len(points_list) / \ (len(multiprocessing.active_children())*2*5)) similarities = self.pool.imap(ScaleSpaceWrapper(float(self.kernel_scale)), itertools.combinations_with_replacement(points_list,2), work_unit_size) #distances = self.pool.imap(average_pairing_distance, # itertools.combinations_with_replacement(points_list,2), # work_unit_size) self.distances = [[0.0 for p in range(len(points_list))] for q in range(len(points_list))] #for ((i,j),similarity,distance) in itertools.izip(ij_iterator, similarities, distances) : for ((i,j),similarity) in itertools.izip(ij_iterator, similarities) : self.distances[i][j] = Distance(None, similarity, None, None) #distance) self.distances[j][i] = Distance(None, similarity, None, None) #distance)
def __init__( self, fid_cosmo, fid_survey, params, probes, margin_params=[], cutNonLinearScales=None, lmax=10000, nl=200, lmin=2, diagonal=False, ): """ Initializes a tomographic Fisher Matrix using the probes given in probes """ self.probes = probes # Calls super class initialization super(fisherTomo, self).__init__(fid_cosmo, fid_survey, params, margin_params) self.diagonal = diagonal # Create a list of redshift bins if diagonal: self.bins = [] for i in range(self.fid_surv.nzbins): self.bins.append((i, i)) else: self.bins = list(itertools.combinations_with_replacement(range(self.fid_surv.nzbins), r=2)) # Create a list of spectra from the probes self.crossprobes = list(itertools.combinations_with_replacement(probes, r=2)) # Create list of power spectra from probes and redshift bins self.cls = list(itertools.product(self.crossprobes, self.bins)) # Compute l range for each redshift bin self.lmax = zeros(len(self.cls)) for i in range(len(self.cls)): zmin = min(self.fid_surv.zbins[self.cls[i][1][0]].zmed, self.fid_surv.zbins[self.cls[i][1][1]].zmed) if cutNonLinearScales is None: self.lmax[i] = lmax else: if cutNonLinearScales is "optimistic": kmax = 0.25 else: kmax = min( self.fid_surv.zbins[self.cls[i][1][0]].kmax_lin, self.fid_surv.zbins[self.cls[i][1][1]].kmax_lin ) self.lmax[i] = kmax * self.fid_cosmo.a2chi(z2a(zmin)) lmax = self.lmax.max() # Generating an hybrid array self._l = logspace(0, log10(lmax), nl) for i in range(nl): if self._l[i] <= (i + lmin): self._l[i] = i + lmin self._nl = len(self._l)
def gen_filtred(n, start = 1): #n - potencia de 10 #combinações de números possíveis simetricamente combs = reduce(list.__add__, [[(x, y) for y in range(0, 10) if (x ^ y) & 1] for x in range(0, 10)]) exp = start while exp < n: tamanho = len(str(10 ** exp))//2 if exp & 1 == 1: #expoente impar na base 10 -> tamanho par for comb in combinations_with_replacement(combs, tamanho): for perm in set(permutations(comb)): first = perm[0] head, tail = first if head == 0 or tail == 0: continue index = exp newnum = 0 for mostnum, lessnum in perm: newnum += mostnum * 10 ** index + lessnum * 10 ** abs(index - exp) index -= 1 yield newnum else: #expoente par na base 10 -> tamanho impar for comb in combinations_with_replacement(combs, tamanho): for perm in set(permutations(comb)): first = perm[0] head, tail = first if head == 0 or tail == 0: continue for middle in range(10): #print('Comb: {}| Perm: {}'.format(comb, perm)) index = exp newnum = middle * 10 ** (exp // 2) for mostnum, lessnum in perm: newnum += mostnum * 10 ** index + lessnum * 10 ** abs(index - exp) index -= 1 yield newnum exp += 1
def _full_cubic(point): ''' degree = 3 ''' return [list(i) for i in range(point)] + \ list(combinations_with_replacement(range(point), 2)) + \ list(combinations_with_replacement(range(point), 3))
def main(): pl = list(itertools.combinations_with_replacement([1,2,3,4], 9)) cl = list(itertools.combinations_with_replacement([1,2,3,4,5,6], 6)) factorial_9 = factorial(9) factorial_6 = factorial(6) p_win = 0 for p in pl: p_sum = sum(p) for c in cl: c_sum = sum(c) if p_sum > c_sum: p_denominator = 1 for i in set(p): p_denominator *= factorial(p.count(i)) p_products = factorial_9 / p_denominator c_denominator = 1 for i in set(c): c_denominator *= factorial(c.count(i)) c_products = factorial_6 / c_denominator p_win += p_products * c_products n = (4**9) * (6**6) print n, p_win, float(p_win) / n print round(float(p_win) / n, 7)
def test_combinations_with_replacement_shortcases(self): from itertools import combinations_with_replacement assert list(combinations_with_replacement([-12], 2)) == [(-12, -12)] assert list(combinations_with_replacement("AB", 3)) == [ ("A", "A", "A"), ("A", "A", "B"), ("A", "B", "B"), ("B", "B", "B")] assert list(combinations_with_replacement([], 2)) == [] assert list(combinations_with_replacement([], 0)) == [()]
def find_sicherman_dice_brute_force(): sichermanDice = [] for die1 in itertools.combinations_with_replacement(range(0, 6), 6): if not is_valid_distribution_single(die1): continue for die2 in itertools.combinations_with_replacement(range(0, 11), 6): if not is_valid_distribution_single(die2): continue if not is_valid_distribution_both(die1, die2): continue if is_distribution_equal(die1, die2): sichermanDice.append((die1, die2)) return sichermanDice
def buildMarketDeck(self): from random import shuffle from itertools import combinations_with_replacement self.market = [] # Particular Artifact + Commodity artType = ['bat','book','bear','balloon','glasses','game'] for i in artType: anyComArt = [[[i,1],['energy',1]], [[i,1],['water',1]],[[i,1],['food',1]], [[i,1],['bliss',1]]] self.market.append(anyComArt) # 4 Commodity + Artifact comType = ['energy','water','food','bliss'] for i in comType: anyArtCom = [[[i,4],['bat',1]], [[i,4],['book',1]],[[i,4],['bear',1]], [[i,4],['balloon',1]],[[i,4],['glasses',1]], [[i,4],['game',1]]] self.market.append(anyArtCom) # 4 Commodity + Resource resType = ['gold','stone','brick'] comType.remove('bliss') for i in comType: for j in resType: self.market.append([[[i,4],[j,1]]]) resCom = zip(comType,resType) for i in resCom: self.market.remove([[[i[0],4],[i[1],1]]]) # Extraneous Markets anyResBliss = [[['bliss',4],['gold',1]], [['bliss',4],['stone',1]],[['bliss',4],['brick',1]]] self.market.append(anyResBliss) anyArtRes = list(combinations_with_replacement([['gold',1],['stone',1],['brick',1], ['bat',1],['book',1],['bear',1], ['balloon',1],['glasses',1],['game',1]],2)) anyTwoRes = list(combinations_with_replacement([['gold',1],['stone',1],['brick',1]],2)) for i in anyTwoRes: anyArtRes.remove(i) anyTwoArt = list(combinations_with_replacement([['bat',1],['book',1],['bear',1], ['balloon',1],['glasses',1],['game',1]],2)) for i in anyTwoArt: anyArtRes.remove(i) # self.market.append(anyArtRes) # ^^ this market has too many options embedded in it for right now shuffle(self.market) self.market = self.market[:6]
def get_scores(std_true, y_true): best_diff = np.inf combs = list(combinations_with_replacement([1,2,3,4],3)) + list(combinations_with_replacement([1,2,3,4],4)) + list(combinations_with_replacement([1,2,3,4],5)) for item in combs: if np.median(item) == y_true: diff = np.abs(np.std(item) - std_true) if diff < best_diff: best_diff = diff best_match = list(item) if best_diff < 1e-8: break return best_match
def compute_distances(self) : if self.pool == None : results = itertools.imap(segment_distance, itertools.combinations_with_replacement(self.segments.segments,2)) else : results = self.pool.imap(segment_distance, itertools.combinations_with_replacement(self.segments.segments,2), len(self.segments.segments) * (len(self.segments.segments) + 1) / \ (10.0 * len(multiprocessing.active_children()))) self.distances = [[None for x in self.segments.segments] for y in self.segments.segments] print for ((i,j),distance) in itertools.izip(itertools.combinations_with_replacement(range(len(self.segments.segments)),2), results) : self.distances[i][j] = distance self.distances[j][i] = distance
def getHKL(sys, n=3): if sys.lower() == "bcc": fxn = isBCC elif sys.lower() =="fcc": fxn = isFCC elif sys.lower() =="hcp": fxn = isHCP y = [[x[0][1], x[0][0], x[1]] for x in product(combinations_with_replacement(range(n+1),2),range(n+1))] return [tuple(x) for x in y if fxn(x)] else: warn("No crystal system given.", SyntaxWarning) return [] return [x for x in combinations_with_replacement(range(n+1), 3) if fxn(x)]
def run(): ingredient, ingredientList = parseData() #Part 1 maxScore = 0 for possible in itertools.combinations_with_replacement(ingredientList, 100): maxScore = max(scoreOfCookie(possible,ingredient, ingredientList), maxScore) print "Pt1. Best Cookie Score is {0}".format(maxScore) #Part 2 maxScore = 0 for possible in itertools.combinations_with_replacement(ingredientList, 100): maxScore = max(scoreOfCookie(possible,ingredient, ingredientList, True), maxScore) print "Pt2. Best Cookie Score is {0}".format(maxScore)
def compute_kernel(self) : if self.gamma == 'cv' : seed = 0xdeadbeef while self.kernel_fun == None : try : # search for the correct gamma and C value using cross validation from sklearn import svm from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.cross_validation import train_test_split indices = xrange(0, len(self.max_labels)) if self.learning[0] != None : train_indices = [i for i in indices if self.learning[i] == 'train'] else : train_indices, test_indices = train_test_split(indices, train_size=self.config.learning_split, random_state=seed) train_labels = [self.max_labels[i] for i in train_indices] train_segments = [self.segments[i] for i in train_indices] C_range = numpy.logspace(-10, 10, 20) gamma_range = numpy.logspace(-10, 10, 20) param_grid = dict([("gamma", gamma_range), ("C", C_range)]) cv = StratifiedShuffleSplit(train_labels, n_iter=5, test_size=0.2, random_state=seed) grid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv) grid.fit(train_segments, train_labels) print("RBFKernel : The best parameters are %s with a score of %0.2f" % (grid.best_params_, grid.best_score_)) self.config.learning_C = grid.best_params_['C'] self.config.kernel_gamma = grid.best_params_['gamma'] self.gamma = grid.best_params_['gamma'] self.kernel_fun = RBFEntryWrapper(self.gamma) except ValueError as e : print "ValueError (%s) in cv search, trying again (%x)" % (e, seed) random_state = os.urandom(4) seed = ord(random_state[0]) + 256 * (ord(random_state[1]) + 256 * (ord(random_state[2]) + 256 * ord(random_state[3]))) self.kernel_fun = None segment_iter = itertools.combinations_with_replacement(self.segments, 2) if (self.pool == None) : value_iter = itertools.imap(self.kernel_fun, segment_iter) else : value_iter = self.pool.imap(self.kernel_fun, segment_iter, max(1, len(self.segments) * (len(self.segments) + 1) / (5 * 2 * len(multiprocessing.active_children())))) self.kernel_matrix = [[0.0 for x in range(len(self.segments))] for y in range(len(self.segments))] for ((i,j), val) in itertools.izip(itertools.combinations_with_replacement(range(len(self.segments)), 2), value_iter) : self.kernel_matrix[i][j] = val self.kernel_matrix[j][i] = val
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self.selectedElements = self.configuration['atom_selection']['n_atoms_per_element'].keys() self.indexToSymbol = numpy.array([self.selectedElements.index(self.configuration['atom_selection']['index_to_symbol'][i]) for i in self.configuration['atom_selection']['indexes']], dtype = numpy.int32) lut = atomindex_to_moleculeindex(self.configuration['trajectory']['instance'].universe) self.indexToMolecule = numpy.array([lut[i] for i in self.configuration['atom_selection']['indexes']], dtype=numpy.int32) nElements = self.configuration['atom_selection']['n_selected_elements'] # The histogram of the intramolecular distances. self.hIntra = numpy.zeros((nElements,nElements,len(self.configuration['r_values']['mid_points'])),dtype=numpy.float64) # The histogram of the intermolecular distances. self.hInter = numpy.zeros((nElements,nElements,len(self.configuration['r_values']['mid_points'])),dtype=numpy.float64) self.scaleconfig = numpy.zeros((self.configuration['atom_selection']['n_groups'],3), dtype=numpy.float64) self.averageDensity = 0.0 self._concentrations = {} for k in self.configuration['atom_selection']['n_atoms_per_element'].keys(): self._concentrations[k] = 0.0 self._elementsPairs = sorted(itertools.combinations_with_replacement(self.configuration['atom_selection']['contents'].keys(),2)) if not self.configuration['trajectory']['instance'].universe.is_periodic: raise Error("Pair distribution function cannot be calculated for infinite universe trajectories")
def test_combinations_with_replacement(self): from itertools import combinations_with_replacement raises(TypeError, combinations_with_replacement, "abc") raises(TypeError, combinations_with_replacement, "abc", 2, 1) raises(TypeError, combinations_with_replacement, None) raises(ValueError, combinations_with_replacement, "abc", -2) assert list(combinations_with_replacement("ABC", 2)) == [("A", "A"), ("A", 'B'), ("A", "C"), ("B", "B"), ("B", "C"), ("C", "C")]
def get_problem_combinator(index, n, num_problems=None): """ Returns a function that combines *n* problems from *index* to get the given number of combined problems selected at random. """ index = index.values() pool = range(len(index)) if num_problems is None: # Get all combinations. combinations = [i for i in itertools.combinations_with_replacement(pool, n)] else: # Set seed to make sure that pseudo-random sequence is reproducible. random.seed(0) combinations = set() while len(combinations) < num_problems: combinations.add(random_combination_with_replacement(pool, n)) def combine_problems(dirname): composite_index = OrderedDict() for indices in combinations: merged_model, best_obj = merge_models([index[i] for i in indices]) name = '-'.join(['{:02}'.format(i + 1) for i in indices]) filename = name + '.mod' path = os.path.join(dirname, filename) with open(path, 'w') as f: ampl.pretty_print(f, merged_model) composite_index[name] = {'best_obj': best_obj, 'path': path} return composite_index return combine_problems
def stack_powers(num_covariates, deg, keys): generators = [basis_vector(num_covariates+1, i) for i in range(num_covariates+1)] # All combinations of degrees powers = map(sum, combinations_with_replacement(generators, deg)) # remove some powers we don't like # first find the index corresponding to our rzero-like term # the plus 1 is because the first term in the column is 1s if 'one_over_rzero' in keys: indx = keys.index('one_over_rzero') + 1 elif 'rzero' in keys: indx = keys.index('rzero') + 1 else: # skip and move on indx = -1 if indx > -1: # we want to cut anything with rzero dep > 2 powers_temp = [] for p in powers: # any combo of variable dep > 4 and no rzero if sum(p) - p[0] - p[indx] > 4: continue # rzero dep > 2 and not another variable if p[indx] > 2 and p[indx] + p[0] != sum(p): continue # if rzero is by itself and > 3 if p[indx] > 3 and sum(p) - p[0] - p[indx] == 0: continue powers_temp.append(p) powers = powers_temp return powers
def multicombinations2(iterable): """ Convenience shortcut, for the name, see the Wikipedia article on Combination. https://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition """ return itertools.combinations_with_replacement(iterable, 2)
def get_symbol_list(rank, dim=6): """ Returns a symbolic representation of the voigt-notation tensor that places identical symbols for entries related by index transposition, i. e. C_1121 = C_1211 etc. Args: dim (int): dimension of matrix/tensor, e. g. 6 for voigt notation and 3 for standard rank (int): rank of tensor, e. g. 3 for third-order ECs Returns: c_vec (array): array representing distinct indices c_arr (array): array representing tensor with equivalent indices assigned as above """ indices = list( itertools.combinations_with_replacement(range(dim), r=rank)) c_vec = np.zeros(len(indices), dtype=object) c_arr = np.zeros([dim]*rank, dtype=object) for n, idx in enumerate(indices): c_vec[n] = sp.Symbol('c_'+''.join([str(i) for i in idx])) for perm in itertools.permutations(idx): c_arr[perm] = c_vec[n] return c_vec, c_arr
def generate_children(self): #import warnings #warnings.warn('Duplicating children') if self.p.digits == self.q.digits: digits_to_add = list(itertools.combinations_with_replacement(xrange(BASE), 2)) else: digits_to_add = list(itertools.product(xrange(BASE), repeat=2)) p_digits = self.p.digits q_digits = self.q.digits children = [] for dta in digits_to_add: new_p_digits = p_digits[:] new_p_digits.append(dta[0]) new_q_digits = q_digits[:] new_q_digits.append(dta[1]) child = Product(new_p_digits, new_q_digits) # Old code #child = self.copy() #child.p._digits.append(dta[0]) #child.q._digits.append(dta[1]) children.append(child) return children
def __iter__(self): """ An iterator for ``self``. This generates the rooted trees of given size. The algorithm first picks a partition for the sizes of subtrees, then picks appropriate tuples of smaller trees. EXAMPLES:: sage: from sage.combinat.rooted_tree import * sage: RootedTrees(1).list() [[]] sage: RootedTrees(2).list() [[[]]] sage: RootedTrees(3).list() [[[[]]], [[], []]] sage: RootedTrees(4).list() [[[[[]]]], [[[], []]], [[], [[]]], [[], [], []]] """ if self._n == 1: yield self._element_constructor_([]) return from sage.combinat.partition import Partitions from itertools import combinations_with_replacement, product for part in Partitions(self._n - 1): mults = part.to_exp_dict() choices = [] for p, mp in mults.items(): lp = self.__class__(p).list() new_choice = [list(z) for z in combinations_with_replacement(lp, mp)] choices.append(new_choice) for c in product(*choices): yield self.element_class(self._parent_for, sum(c, []))
def threePointsToStandard(e, p, q, r): """Return a projective transformation that maps three points on a conic to the conic xy + yz + xz = 0. Keyword arguments: e -- a projective conic p -- the first point on e q -- the second point on e r -- the third point on e """ coeffs = e p, q, r = np.matrix(p), np.matrix(q), np.matrix(r) # Determine a matrix A associated with a projective transformation that # maps P, Q, and R onto [1, 0, 0], [0, 1, 0], and [0, 0, 1], respectively. A = np.linalg.inv(np.vstack([p, q, r])) # Determine the equation bx'y' + fx'z' + gy'z' = 0 of t(E), for some real # numbers b, f, and g. M = sum([coeff * u.T * v for coeff, (u, v) in zip(coeffs, combinations_with_replacement((p, q, r), 2))]) # Get B from M by adding like terms to find b, f, and g and then # constructing a diagonal matrix from the flat [1/g, 1/f, 1/b]. B = np.diagflat([1 / (u + v) for u, v in reversed(zip(np.array(M)[np.triu_indices(3, 1)], np.array(M)[np.tril_indices(3, -1)]))]) return B * A
def brute_force(sky, num_halos=1, dx=50, dw=30, xmin=25, xmax=XMAX, ymin=25, ymax=YMAX, wmin=10, wmax=200): x = [float(i*dx) + xmin for i in range(0, int((xmax-xmin)/dx))] y = [float(i*dx) + ymin for i in range(0, int((ymax-ymin)/dx))] weights = [float(i*dw) + wmin for i in range(0, int((wmax-wmin)/dw))] coords = [(xx, yy) for xx in x for yy in y] ll_best = None c_best = None w_best = None prior = mass_prior if num_halos == 1 else semi_mass_prior lls = [] for clist in itertools.combinations(coords, num_halos): penalty = 0 c = list(clist) for w in itertools.combinations_with_replacement(weights, num_halos): w = list(w) ll = sky_likelihood(sky, c, w, prior=prior) lls.append((ll, c, w)) if ll_best is None or ll > ll_best: ll_best = ll c_best = clist w_best = w lls.sort(key = lambda x: -x[0]) return lls
def create_atomic_orbital_names(orbitals): """Generate all atomic orbital names that could be used by Molpro. The names are returned in a dictionary, organized by subshell (S, P, D and so on). """ # We can write out the first two manually, since there are not that many. atomic_orbital_names = { 'S': ['s', '1s'], 'P': ['x', 'y', 'z', '2px', '2py', '2pz'], } # Although we could write out all names for the other subshells, it is better # to generate them if we need to expand further, since the number of functions quickly # grows and there are both Cartesian and spherical variants to consider. # For D orbitals, the Cartesian functions are xx, yy, zz, xy, xz and yz, and the # spherical ones are called 3d0, 3d1-, 3d1+, 3d2- and 3d2+. For F orbitals, the Cartesians # are xxx, xxy, xxz, xyy, ... and the sphericals are 4f0, 4f1-, 4f+ and so on. for i, orb in enumerate(orbitals): # Cartesian can be generated directly by combinations. cartesian = list(map(''.join, list(itertools.combinations_with_replacement(['x', 'y', 'z'], i+2)))) # For spherical functions, we need to construct the names. pre = str(i+3) + orb.lower() spherical = [pre + '0'] + [pre + str(j) + s for j in range(1, i+3) for s in ['-', '+']] atomic_orbital_names[orb] = cartesian + spherical return atomic_orbital_names
def hessian_matrix(image, sigma=1, mode="constant", cval=0): """Compute Hessian matrix. The Hessian matrix is defined as:: H = [Hxx Hxy] [Hxy Hyy] which is computed by convolving the image with the second derivatives of the Gaussian kernel in the respective x- and y-directions. Parameters ---------- image : ndarray Input image. sigma : float Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional How to handle values outside the image borders. cval : float, optional Used in conjunction with mode 'constant', the value outside the image boundaries. Returns ------- Hxx : ndarray Element of the Hessian matrix for each pixel in the input image. Hxy : ndarray Element of the Hessian matrix for each pixel in the input image. Hyy : ndarray Element of the Hessian matrix for each pixel in the input image. Examples -------- >>> from skimage.feature import hessian_matrix >>> square = np.zeros((5, 5)) >>> square[2, 2] = 4 >>> Hxx, Hxy, Hyy = hessian_matrix(square, sigma=0.1) >>> Hxy array([[ 0., 0., 0., 0., 0.], [ 0., 1., 0., -1., 0.], [ 0., 0., 0., 0., 0.], [ 0., -1., 0., 1., 0.], [ 0., 0., 0., 0., 0.]]) """ image = img_as_float(image) gaussian_filtered = ndi.gaussian_filter(image, sigma=sigma, mode=mode, cval=cval) gradients = np.gradient(gaussian_filtered) axes = range(image.ndim) H_elems = [np.gradient(gradients[ax0], axis=ax1) for ax0, ax1 in combinations_with_replacement(axes, 2)] if image.ndim == 2: # The legacy 2D code followed (x, y) convention, so we swap the axis # order to maintain compatibility with old code H_elems.reverse() return H_elems
def generate_combinations(players_to_combine,length): if not isinstance(players_to_combine,(list,tuple)): raise TicTacToeException( 'players_to_combine needs to be a list with 1 or 2 '\ 'items : {} as player_0 , {} as player_1 and ' \ '{} as player_2 .No other items besides '\ 'those .'.format(FREE_SPACE,PLAYER_1,PLAYER_2)) for p in players_to_combine: verify_player(player=p) combinations = [] for pattern in combinations_with_replacement(players_to_combine,length): pattern_combinations = player_combinations( player_0 = pattern.count(FREE_SPACE), player_1 = pattern.count(PLAYER_1) , player_2 = pattern.count(PLAYER_2) ) for combination in pattern_combinations: p = [combination.count(FREE_SPACE), combination.count(PLAYER_1) , combination.count(PLAYER_2)] if p not in combinations: combinations.append(p) return combinations
def process(): index = 0 #Generate an array corresponding to the k-vertices we want to add to c7 for add in combinations_with_replacement(range(4), 7): print(add) #We can have at most 3 Z's and 2 Y's, making 5 possible vertices we can add if count(add) > 5: break for thisPermutation in permutations(add): #copy initial graph (c7) and add vertices #self.g = BASE.copy() g = make_cycle(7) add_vertices(g, thisPermutation) check = True #we want our graph to remain {4k1,c4,c6}-free for H in FORBIDDEN: if induced_subgraph(g, H): check = False break if check: #log it f = File(DIRECTORY, G=g, logger=LOGGER, base="C5-") fp = f.save() if fp is not None: index += 1 print("Created Graph: %d" % index)
import itertools #N = int(input()) N,M,Q=(int(x) for x in input().split()) # A = [int(x) for x in input().split()] max_ans = 0 _input = [] A = list(range(1,M+1)) for i in range(Q): a = [int(x) for x in input().split()] _input.append(a) for v in itertools.combinations_with_replacement(A,N): tmp = 0 for i in _input: if v[i[1]-1] - v[i[0]-1] == i[2]: tmp += i[3] max_ans = max(max_ans,tmp) print(max_ans) #itertools.combinations()
# ref # https://medium.com/@jasonrigden/a-guide-to-python-itertools-82e5a306cdf8 data = [5, 2, 6, 4, 5, 9, 1] result = itertools.accumulate(data, max) for each in result: print(each) shapes = ['circle', 'triangle', 'square',] result = itertools.combinations(shapes, 2) for each in result: print(each) shapes = ['circle', 'triangle', 'square',] result = itertools.combinations_with_replacement(shapes, 2) for each in result: print(each) colors = ['red', 'orange', 'yellow', 'green', 'blue'] shapes = ['circle', 'triangle', 'square', 'pentagon'] result = itertools.chain(colors, shapes) for each in result: print(each) data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1] result = itertools.dropwhile(lambda x: x<5, data) for each in result: print(each) data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import itertools n, m, q = map(int, input().split()) li = [] for i in range(q): li.append(list(map(int, input().split()))) Alist = list(itertools.combinations_with_replacement(range(1, m + 1), n)) answer = [] for i in range(len(Alist)): score = 0 for j in range(q): b = li[j][1] - 1 a = li[j][0] - 1 if (Alist[i][b] - Alist[i][a] == li[j][2]): score += li[j][3] answer.append(score) print(max(answer))
def classify_pde(eq, func=None, dict=False, **kwargs): """ Returns a tuple of possible pdsolve() classifications for a PDE. The tuple is ordered so that first item is the classification that pdsolve() uses to solve the PDE by default. In general, classifications near the beginning of the list will produce better solutions faster than those near the end, though there are always exceptions. To make pdsolve use a different classification, use pdsolve(PDE, func, hint=<classification>). See also the pdsolve() docstring for different meta-hints you can use. If ``dict`` is true, classify_pde() will return a dictionary of hint:match expression terms. This is intended for internal use by pdsolve(). Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by doing help(pde.pde_hintname), where hintname is the name of the hint without "_Integral". See diofant.pde.allhints or the diofant.pde docstring for a list of all supported hints that can be returned from classify_pde. Examples ======== >>> u = f(x, y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0) >>> classify_pde(eq) ('1st_linear_constant_coeff_homogeneous',) """ prep = kwargs.pop('prep', True) if func and len(func.args) != 2: raise NotImplementedError('Right now only partial ' 'differential equations of two ' 'variables are supported') if prep or func is None: prep, func_ = _preprocess(eq, func) if func is None: func = func_ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs f = func.func x = func.args[0] y = func.args[1] fx = f(x, y).diff(x) fy = f(x, y).diff(y) # TODO : For now pde.py uses support offered by the ode_order function # to find the order with respect to a multi-variable function. An # improvement could be to classify the order of the PDE on the basis of # individual variables. order = ode_order(eq, f(x, y)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {'order': order} if not order: if dict: matching_hints['default'] = None return matching_hints else: return () eq = expand(eq) a = Wild('a', exclude=[f(x, y)]) b = Wild('b', exclude=[f(x, y), fx, fy, x, y]) c = Wild('c', exclude=[f(x, y), fx, fy, x, y]) d = Wild('d', exclude=[f(x, y), fx, fy, x, y]) e = Wild('e', exclude=[f(x, y), fx, fy]) n = Wild('n', exclude=[x, y]) # Try removing the smallest power of f(x,y) # from the highest partial derivatives of f(x,y) reduced_eq = None if eq.is_Add: var = set(combinations_with_replacement((x, y), order)) dummyvar = var.copy() power = None for i in var: coeff = eq.coeff(f(x, y).diff(*i)) if coeff != 1: match = coeff.match(a * f(x, y)**n) if match and match[a]: power = match[n] dummyvar.remove(i) break dummyvar.remove(i) if power: den = f(x, y)**power reduced_eq = Add(*[arg / den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: reduced_eq = collect(reduced_eq, f(x, y)) r = reduced_eq.match(b * fx + c * fy + d * f(x, y) + e) if r: if not r[e]: # Linear first-order homogeneous partial-differential # equation with constant coefficients r.update({'b': b, 'c': c, 'd': d}) matching_hints['1st_linear_constant_coeff_homogeneous'] = r else: if r[b]**2 + r[c]**2 != 0: # Linear first-order general partial-differential # equation with constant coefficients r.update({'b': b, 'c': c, 'd': d, 'e': e}) matching_hints['1st_linear_constant_coeff'] = r matching_hints['1st_linear_constant_coeff_Integral'] = r else: b = Wild('b', exclude=[f(x, y), fx, fy]) c = Wild('c', exclude=[f(x, y), fx, fy]) d = Wild('d', exclude=[f(x, y), fx, fy]) r = reduced_eq.match(b * fx + c * fy + d * f(x, y) + e) if r: r.update({'b': b, 'c': c, 'd': d, 'e': e}) matching_hints['1st_linear_variable_coeff'] = r # Order keys based on allhints. retlist = [] for i in allhints: if i in matching_hints: retlist.append(i) if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for pdsolve(). Use an ordered dict in Py 3. matching_hints['default'] = None matching_hints['ordered_hints'] = tuple(retlist) for i in allhints: if i in matching_hints: matching_hints['default'] = i break return matching_hints else: return tuple(retlist)
def hessian(self, device, params=None, **options): r"""Compute the Hessian of the parametrized quantum circuit recorded by the quantum tape. The quantum tape can be interpreted as a simple :math:`\mathbb{R}^m \to \mathbb{R}^n` function, mapping :math:`m` (trainable) gate parameters to :math:`n` measurement statistics, such as expectation values or probabilities. By default, the Hessian will be computed with respect to all parameters on the quantum tape. This can be modified by setting the :attr:`~.trainable_params` attribute of the tape. The Hessian can be currently computed using only the ``'analytic'`` method. Args: device (.Device, .QubitDevice): a PennyLane device that can execute quantum operations and return measurement statistics params (list[Any]): The quantum tape operation parameters. If not provided, the current tape parameter values are used (via :meth:`~.get_parameters`). Keyword Args: method="analytic" (str): The differentiation method. Currently only supports ``"analytic"``. s1=pi/2 (float): the size of the shift for index i in the parameter-shift Hessian computations s2=pi/2 (float): the size of the shift for index j in the parameter-shift Hessian computations Returns: array[float]: 2-dimensional array of shape ``(tape.num_params, tape.num_params)`` **Example** .. code-block:: python n_wires = 5 weights = [2.73943676, 0.16289932, 3.4536312, 2.73521126, 2.6412488] with QubitParamShiftTape() as tape: for i in range(n_wires): qml.RX(weights[i], wires=i) qml.CNOT(wires=[0, 1]) qml.CNOT(wires=[2, 1]) qml.CNOT(wires=[3, 1]) qml.CNOT(wires=[4, 3]) qml.expval(qml.PauliZ(1)) If parameters are not provided, the existing tape parameters are used: >>> dev = qml.device("default.qubit", wires=n_wires) >>> tape.hessian(dev) array([[ 0.79380556, 0.05549219, 0.10891309, -0.1452963, 0.], [ 0.05549219, 0.79380556, -0.04208544, 0.05614438, 0.], [ 0.10891309, -0.04208544, 0.79380556, 0.11019314, 0.], [-0.1452963, 0.05614438, 0.11019314, 0.79380556, 0.], [ 0., 0., 0., 0., 0.]]) Parameters can be optionally passed during execution: >>> tape.hessian(dev, params=[1.0, 1.0, 2.0, 0, 0]) array([[ 0.12148432, -0.29466251, 0.41341091, 0., 0.], [-0.29466251, 0.12148432, 0.41341091, 0., 0.], [ 0.41341091, 0.41341091, 0.12148432, 0., 0.], [ 0., 0., 0., 0.12148432, 0.], [ 0., 0., 0., 0., 0.]]) Parameters provided for execution are temporary, and do not affect the tapes' parameters in-place: >>> tape.get_parameters() [2.73943676, 0.16289932, 3.4536312, 2.73521126, 2.6412488] If a tape has no trainable parameters, the Hessian will be empty: >>> tape.trainable_params = {} >>> tape.hessian(dev) array([], shape=(0, 0), dtype=float64) """ if any(m.return_type is State for m in self.measurements): raise ValueError("The Hessian method does not support circuits that return the state") method = options.get("method", "analytic") if method != "analytic": raise ValueError(f"Unknown Hessian method '{method}'") if params is None: params = self.get_parameters() params = np.array(params) # perform gradient method validation diff_methods = self._grad_method_validation(method) if not self._has_trainable_params(params, diff_methods): # Either all parameters have grad method 0, or there are no trainable # parameters. Simply return an empty Hessian. return np.zeros((len(params), len(params)), dtype=float) # The parameter-shift Hessian implementation currently only supports # the two-term parameter-shift rule. Raise an error for unsupported operations. supported_ops = ( "RX", "RY", "RZ", "Rot", "PhaseShift", "ControlledPhaseShift", "MultiRZ", "PauliRot", "U1", "U2", "U3", "SingleExcitationMinus", "SingleExcitationPlus", "DoubleExcitationMinus", "DoubleExcitationPlus", ) for idx, info in self._par_info.items(): op = info["op"] if idx in self.trainable_params and op.name not in supported_ops: raise ValueError( f"The operation {op.name} is currently not supported for the " f"parameter-shift Hessian.\nPlease decompose the operation in your " f"QNode by replacing it with '{op.__str__().replace('(', '.decomposition(')}'" ) # some gradient methods need the device or the device wires options["device"] = device options["dev_wires"] = device.wires # collect all circuits (tapes) and postprocessing functions required # to compute the Hessian all_tapes = [] reshape_info = [] processing_fns = [] nonzero_grad_idx = [] # From Schwarz's theorem, the Hessian will be symmetric, so we # can compute the upper triangular part only and symmetrize # the final Hessian. for i, j in itertools.combinations_with_replacement(range(len(diff_methods)), 2): if diff_methods[i] == "0" or diff_methods[j] == "0": continue nonzero_grad_idx.append((i, j)) tapes, processing_fn = self.hessian_pd(i, j, params=params, **options) processing_fns.append(processing_fn) # we create a flat list here to feed at once to the device all_tapes.extend(tapes) # to extract the correct result for this parameter later, remember the number of tapes reshape_info.append(len(tapes)) # execute all tapes at once results = device.batch_execute(all_tapes) hessian = None start = 0 for (i, j), processing_fn, res_len in zip(nonzero_grad_idx, processing_fns, reshape_info): # extract the correct results from the flat list res = results[start : start + res_len] start += res_len # postprocess results to compute the gradient g = self._flatten_processing_result(processing_fn(res)) if hessian is None: # create the Hessian matrix if self.output_dim is not None: hessian = np.zeros( (len(params), len(params), np.prod(self.output_dim)), dtype=float ) else: hessian = np.zeros((len(params), len(params)), dtype=float) if i == j: hessian[i, i] = g else: hessian[i, j] = hessian[j, i] = g if self.output_dim == 1: hessian = np.squeeze(hessian, axis=-1) return hessian