def predict(self, batch_inputs, positive_class_label=const.BAD): model_out = self(batch_inputs) predictions = self.outputs.decode_outputs(model_out, batch_inputs, positive_class_label) if const.TARGET_TAGS in predictions and const.GAP_TAGS in predictions: targetgaps = [] for target, gaps in zip(predictions[const.TARGET_TAGS], predictions[const.GAP_TAGS]): # Order is important (gaps, then target) targetgaps.append(list(more_itertools.roundrobin(gaps, target))) predictions[const.TARGETGAPS_TAGS] = targetgaps targetgaps_labels = [] for target, gaps in zip( predictions[f'{const.TARGET_TAGS}_labels'], predictions[f'{const.GAP_TAGS}_labels'], ): # Order is important (gaps, then target) targetgaps_labels.append( list(more_itertools.roundrobin(gaps, target))) predictions[f'{const.TARGETGAPS_TAGS}_labels'] = targetgaps_labels return predictions
def __structureFinalMessage(self): # Step 4.1: Determine How Many Blocks and Error Correction Codewords are Required ✔️ auxMessagePolynomial = [] for i in range(2, 5, 2): blockSize = eCCWBI[self.errorCorretionLevel][self.version - 1][i + 1] for j in range(eCCWBI[self.errorCorretionLevel][self.version - 1][i]): auxMessagePolynomial.append( self.__messagePolynomial[blockSize * j:blockSize * (j + 1)]) self.__errorCorrectionCodewords.append( self.__generateErrorCorrectionCodewords( auxMessagePolynomial[-1][::-1])) group2 = eCCWBI[self.errorCorretionLevel][ self.version - 1][2] * eCCWBI[self.errorCorretionLevel][self.version - 1][3] self.__messagePolynomial = self.__messagePolynomial[group2:] self.__messagePolynomial = auxMessagePolynomial.copy() # Step 4.2: Intervale the Blocks ✔️ self.__finalMessage = list( roundrobin(*self.__messagePolynomial)) + list( roundrobin(*self.__errorCorrectionCodewords)) # Step 4.3: Convert to Binary ✔️ self.__finalMessage = ''.join('{:08b}'.format(x) for x in self.__finalMessage) # Step 4.4: Add Remainder Bits if Necessary ✔️ self.__finalMessage += '0' * rRBs[self.version - 1]
def join(sep, seq, axis=None): """ Note: zero-length elements will be skipped. """ assert is_array(seq) if isinstance(seq, np.ma.MaskedArray): # print(seq) # raise NotImplementedError pass else: seq = np.asarray(seq) if axis is None: # char Element-wise join return np.char.join(sep, seq) if isinstance(seq, np.ma.MaskedArray): divided = np.rollaxis(seq.filled(""), axis=axis) else: divided = np.rollaxis(seq, axis=axis) return functools.reduce( lambda a, b: np.char.add(a, b), more_itertools.roundrobin(divided, itertools.repeat(sep, len(divided) - 1)))
def start_round_from_player_cards(*player_cards: Sequence[cards.Card], first_player: int, set_aside=None): """ Create a round that will deal to each player the specified sequence of cards. The deck is built in a way so that player i starts with player_cards[i][0] and is dealt the cards in player_cards[i][1:] in order at each successive turn. This assumes that no player is eliminated before the last card in player_cards[i] is dealt to them. :param player_cards: A varargs sequence of card sequences that each player will receive during the round. The first list corresponds to player 0, then player 1, and so on. :param first_player: ID (index) of the first player to play in the round. This is (also) needed to build the deck so that player_cards[i] always corresponds to player i (*not* the i-th player to play). :param set_aside: Which card to set aside in the deck. Default is a new instance of :class:`cards.Princess`. :return: A round with the number of players and deck deduced from ``player_cards``. """ player_cards = player_cards[first_player:] + player_cards[:first_player] stack = list(mitt.roundrobin(*player_cards))[::-1] deck = Deck(stack, set_aside=set_aside or cards.Princess()) round = Round(len(player_cards), deck=deck) round.start(first_player=round.players[first_player]) return round
def createTasksFromSplitParameterGrid(parameter_grid, batch_size): batched_tasks_grouped_by_parameter = [] num_param_combos = 0 for (parameters_id, (agent_parameters, other_parameters)) in enumerate(parameter_grid, 1): # SKIP NON-NULL SAMPLE SIZES THAT ARE LARGE ENOUGH TO CONTAIN ENTIRE GRID (assuming here that sample size None is one of the param choices) # AS THEY WILL GET THE EXACT SAME RESULTS AS THE FULL-GRID SAMPLE (denoted by sample size None) skip_parameters = is_sample_size_redundant( agent_parameters["sample_size"], other_parameters["config"]) if skip_parameters: continue num_param_combos += 1 tasks = createTasksFromParameters(agent_parameters, other_parameters, batch_size=batch_size) # Sticking on the parameters_id to each task so the results from all the tasks # can more easily be grouped by their parameters tasks_with_param_id = [(parameters_id, task) for task in tasks] batched_tasks_grouped_by_parameter.append(tasks_with_param_id) interleaved_tasks = more_itertools.roundrobin( *batched_tasks_grouped_by_parameter) interleaved_tasks_with_task_id = [ (task_id, param_id, task) for (task_id, (param_id, task)) in enumerate(interleaved_tasks, 1) ] return interleaved_tasks_with_task_id, num_param_combos
def order_epoch_instances( self, epoch_instances: Dict[str, Iterable[Instance]] ) -> Iterable[Tuple[str, Instance]]: iterators = [ zip(itertools.cycle([dataset]), iterator) for dataset, iterator in epoch_instances.items() ] return more_itertools.roundrobin(*iterators)
def batch_instances( self, epoch_instances: Dict[str, Iterable[Instance]] ) -> Iterable[List[Instance]]: chunked_iterators = [ _chunked_iterator(iterator, self.batch_size[dataset], self.drop_last) for dataset, iterator in epoch_instances.items() ] return more_itertools.roundrobin(*chunked_iterators)
def frame_trace(filtered_report, plot_type='mean', ax=None): # pragma: no cover """Returns a plot displaying the voltage of a node or a compartment as a function of time. Args: plot_type (str): string either `all` or `mean`. `all` will plot the first 15 traces from the group. `mean` will plot the mean value of the node ax: A plot axis object that will be updated Returns: matplotlib.Axis: axis containing the soma's traces. """ # pylint: disable=too-many-locals plt = _get_pyplot() if ax is None: ax = plt.gca() data_units = filtered_report.frame_report.data_units if plot_type == "mean": ax.set_ylabel('Avg volt. [{}]'.format(data_units)) elif plot_type == "all": ax.set_ylabel('Voltage [{}]'.format(data_units)) ax.set_xlabel("Time [{}]".format( filtered_report.frame_report.time_units)) ax.set_xlim([ filtered_report.report.index.min(), filtered_report.report.index.max() ]) if plot_type == "mean": ax.plot(filtered_report.report.T.mean()) elif plot_type == "all": max_per_pop = 15 levels = filtered_report.report.columns.levels slicer = [] # create a slicer that will slice only on the last level of the columns # that is, node_id for the soma report, element_id for the compartment report for i, _ in enumerate(levels): max_ = levels[i][:max_per_pop][-1] slicer.append( slice(None) if i != len(levels) - 1 else slice(None, max_)) data = filtered_report.report.loc[:, tuple(slicer)].T # create [[(pop1, id1), (pop1, id2),...], [(pop2, id1), (pop2, id2),...]] indexes = [[(pop, idx) for idx in data.loc[pop].index] for pop in levels[0]] # try to keep the maximum of ids from each population kept_ids = list(roundrobin(*indexes))[:max_per_pop] for _, row in data.loc[kept_ids].iterrows(): ax.plot(row) else: raise BluepySnapError( "Unknown plot_type {}. Should be 'mean or 'all'.".format( plot_type)) return ax
def pcap_path(metadata, n_packets, use_sll, tmpdir): file_path = os.path.join(tmpdir, "pcap_test.pcap") packets = islice( roundrobin(random_lidar_packets(metadata), random_imu_packets(metadata)), n_packets) pcap.record(packets, file_path, use_sll_encapsulation=use_sll) yield file_path
def _stabilize(self): if not self._forPrint: self._circuit.append(self._insertErrors(), cirq.InsertStrategy.NEW_THEN_INLINE) zStabilizers = [] xStabilizers = [] for y in range(self._d + 1): for x in range(self._d + 1): if ((x + y) % 2 == 0): xStabilizers.append(self._stabilizeX(x, y)) else: zStabilizers.append(self._stabilizeZ(x, y)) self._circuit.append(roundrobin(*zStabilizers), cirq.InsertStrategy.NEW_THEN_INLINE) self._circuit.append(roundrobin(*xStabilizers), cirq.InsertStrategy.NEW_THEN_INLINE) self._step = self._step + 1
def order_epoch_instances( self, epoch_instances: Dict[str, Iterable[Instance]] ) -> Iterable[Tuple[str, Instance]]: grouped_iterators = [ util.lazy_groups_of(zip(itertools.cycle([dataset]), iterator), self.batch_size[dataset]) for dataset, iterator in epoch_instances.items() ] batch_iterator = more_itertools.roundrobin(*grouped_iterators) for batch in batch_iterator: yield from batch
def row_weights(array): option = int(input('Please enter number between 1 - 10: ')) if option == 1: team_one = [80] team_two = [0] elif option == 2: team_one = [100] team_two = [50] elif option == 3: team_one = [50, 70] team_two = [60, 80] elif option == 4: team_one = [13, 49] team_two = [27] elif option == 5: team_one = [70, 75, 91] team_two = [58, 34] elif option == 6: team_one = [29, 67, 19, 96] team_two = [83, 53, 28] elif option == 7: team_one = [0] team_two = [] elif option == 8: team_one = [50, 70] team_two = [60, 80] elif option == 9: team_one = [39, 74, 59, 35] team_two = [84, 18, 72, 61] elif option == 10: team_one = [0, 0] team_two = [1] else: print('The list not exist') team_one_weight = 0 team_two_weight = 0 final_team = list() array = list(roundrobin(team_one, team_two)) for x in team_one: team_one_weight += x for y in team_two: team_two_weight += y final_team = [team_one_weight, team_two_weight] print('Total weight of both list are :', final_team) return f'Your entered {option} this is your list {array} == {final_team}'
def test_pattern(tmpdir, num_nodes, patterns, files): make_files_and_cd(tmpdir, files) runner = CliRunner() if type(patterns) == list: args = list(roundrobin(["--patterns"] * len(patterns), patterns)) result = runner.invoke(cli, args) else: result = runner.invoke(cli, ["--patterns", patterns]) import json pipeline = json.loads(result.output) assert result.exit_code == 0 assert len(pipeline["__default__"]) == num_nodes
def main(mapa): # part1 max_covering = 0 start, max_covering = max(((p,covering(p, mapa)) for p in mapa), key=lambda x:x[1]) print("covering", max_covering-1, "from", start) # part2 mapa.remove(start) angleOrder = lambda x: angleUp(toDir((x[0]-start[0], x[1]-start[1]))) res = sorted(mapa, key=angleOrder) res = (sorted(g, key=lambda x: dist2(x, start)) for _,g in groupby(res, key=angleOrder)) res = list(roundrobin(*res)) print(res) print("200th ",res[199])
def form3_process(form: Form3): ## correct order of checkbox all_choices = form.fields["subjects"]._choices for k, i in enumerate(all_choices): all_choices[k] = [i[1], i[0] in form.cleaned_data["subjects"]] for i, j in zip( (*roundrobin(all_choices[:5], all_choices[5:8], all_choices[8:]), ), [cell for x in doc.tables[3].rows[1:] for cell in x.cells]): if i[1]: j.text = u"\u2611" + " " + i[0] + " " else: j.text = u"\u2610" + " " + i[0] + " "
def zip(args): """Combine 2 files with interleaved pages.""" filesandranges = iohelper.parse_ranges(args[:-1]) outputfilename = args[-1] verbose = staplelib.OPTIONS.verbose if not filesandranges or not outputfilename: raise CommandError('Both input and output filenames are required.') # Make [[file1_p1, file1_p2], [file2_p1, file2_p2], ...]. filestozip = [] for input in filesandranges: pdf = input['pdf'] if verbose: print input['name'] # Empty range means "include all pages". pagerange = input['pages'] or [ (p, iohelper.ROTATION_NONE) for p in range(1, pdf.getNumPages() + 1)] pagestozip = [] for pageno, rotate in pagerange: if 1 <= pageno <= pdf.getNumPages(): if verbose: print "Using page: {} (rotation: {} deg.)".format( pageno, rotate) pagestozip.append( pdf.getPage(pageno - 1).rotateClockwise(rotate)) else: raise CommandError("Page {} not found in {}.".format( pageno, input['name'])) filestozip.append(pagestozip) # Interweave pages. output = PdfFileWriter() for page in more_itertools.roundrobin(*filestozip): output.addPage(page) if os.path.isabs(outputfilename): iohelper.write_pdf(output, outputfilename) else: iohelper.write_pdf(output, staplelib.OPTIONS.destdir + os.sep + outputfilename)
def zip(args): """Combine 2 files with interleaved pages.""" filesandranges = iohelper.parse_ranges(args[:-1]) outputfilename = args[-1] verbose = staplelib.OPTIONS.verbose if not filesandranges or not outputfilename: raise CommandError('Both input and output filenames are required.') # Make [[file1_p1, file1_p2], [file2_p1, file2_p2], ...]. filestozip = [] for input in filesandranges: pdf = input['pdf'] if verbose: print input['name'] # Empty range means "include all pages". pagerange = input['pages'] or [(p, iohelper.ROTATION_NONE) for p in range(1, pdf.getNumPages() + 1)] pagestozip = [] for pageno, rotate in pagerange: if 1 <= pageno <= pdf.getNumPages(): if verbose: print "Using page: {} (rotation: {} deg.)".format( pageno, rotate) pagestozip.append( pdf.getPage(pageno - 1).rotateClockwise(rotate)) else: raise CommandError("Page {} not found in {}.".format( pageno, input['name'])) filestozip.append(pagestozip) # Interweave pages. output = PdfFileWriter() for page in more_itertools.roundrobin(*filestozip): output.addPage(page) if os.path.isabs(outputfilename): iohelper.write_pdf(output, outputfilename) else: iohelper.write_pdf(output, staplelib.OPTIONS.destdir + os.sep + outputfilename)
def test_file_pattern(tmpdir, num_nodes, file_patterns, files): make_files_and_cd(tmpdir, files) runner = CliRunner() if type(file_patterns) == list: args = list( roundrobin(["--file-patterns"] * len(file_patterns), file_patterns)) result = runner.invoke(cli, args) else: result = runner.invoke(cli, ["--file-patterns", file_patterns]) import json pipelines = json.loads(result.output) assert result.exit_code == 0 assert ( len(pipelines["__default__"]) == num_nodes ), f"did not collect all nodes from test using\npattern: {file_patterns}\nfiles: {[file.name for file in file_patterns]}"
def batch_instances( self, epoch_instances: Dict[str, Iterable[Instance]] ) -> Iterable[List[Instance]]: forced_epoch_instances = {dataset: list(iterator) for dataset, iterator in epoch_instances.items()} max_length = max(len(iterator) for iterator in forced_epoch_instances.values()) even_length_epoch_instances = {} for dataset, instances in forced_epoch_instances.items(): even_length_epoch_instances[dataset] = [] cycled_instances = itertools.cycle(instances) for i in range(max_length): even_length_epoch_instances[dataset].append(next(cycled_instances)) even_length_epoch_instances = {dataset: iter(instances) for dataset, instances in even_length_epoch_instances.items()} chunked_iterators = [ _chunked_iterator(iterator, self.batch_size[dataset], self.drop_last) for dataset, iterator in even_length_epoch_instances.items() ] return more_itertools.roundrobin(*chunked_iterators)
def test_uneven_groups(self): """Ensure ordered output from unevenly populated iterables""" self.assertEqual( list(mi.roundrobin("ABCD", [1, 2], range(0))), ["A", 1, "B", 2, "C", "D"] )
def shuffle_twobeds(afbed, bfbed, bbfasta, prefix=None): # Shuffle the two bedfiles together sz = Sizes(bbfasta) sizes = sz.mapping shuffled = "shuffled.bed" border = bfbed.order all = [] afbed.sort(key=afbed.nullkey) totalids = len(sizes) pad = int(math.log10(totalids)) + 1 cj = 0 seen = set() accn = lambda x: "{0}{1:0{2}d}".format(prefix, x, pad) for seqid, aa in afbed.sub_beds(): cj += 1 abeds, bbeds, beds = [], [], [] size = sizes[seqid] ranges = [(x.seqid, x.start, x.end) for x in aa] cranges = range_interleave(ranges, sizes={seqid: size}, empty=True) for crange in cranges: if crange: seqid, start, end = crange bedline = "\t".join(str(x) for x in (seqid, start - 1, end)) abeds.append(BedLine(bedline)) else: abeds.append(None) for a in aa: gapid = a.accn bi, b = border[gapid] if a.strand == "-": b.extra[1] = b.strand = "-" if b.strand == "+" else "+" bbeds.append(b) n_abeds = len(abeds) n_bbeds = len(bbeds) assert n_abeds - n_bbeds == 1, "abeds: {0}, bbeds: {1}".format(n_abeds, n_bbeds) beds = [x for x in roundrobin(abeds, bbeds) if x] if prefix: for b in beds: b.accn = accn(cj) all.extend(beds) seen.add(seqid) # Singletons for seqid, size in sz.iter_sizes(): if seqid in seen: continue bedline = "\t".join(str(x) for x in (seqid, 0, size, accn(cj))) b = BedLine(bedline) cj += 1 if prefix: b.accn = accn(cj) all.append(b) shuffledbed = Bed() shuffledbed.extend(all) shuffledbed.print_to_file(shuffled) return shuffledbed
def test_uneven_groups(self): """Ensure ordered output from unevenly populated iterables""" self.assertEqual(list(mi.roundrobin('ABCD', [1, 2], range(0))), ['A', 1, 'B', 2, 'C', 'D'])
def test_even_groups(self): """Ensure ordered output from evenly populated iterables""" self.assertEqual(list(mi.roundrobin('ABC', [1, 2, 3], range(3))), ['A', 1, 0, 'B', 2, 1, 'C', 3, 2])
def batch_instances( self, epoch_instances: Dict[str, Iterable[Instance]] ) -> Iterable[List[Instance]]: return _chunked_iterator( more_itertools.roundrobin(*epoch_instances.values()), self.batch_size, self.drop_last)
def interleave(*iterables): """ roundrobin('ABC', 'D', 'EF') --> A D E B F C """ return roundrobin(*iterables)
def test_uneven_groups(self): """Ensure ordered output from unevenly populated iterables""" self.assertEqual( list(mi.roundrobin('ABCD', [1, 2], range(0))), ['A', 1, 'B', 2, 'C', 'D'] )
def test_even_groups(self): """Ensure ordered output from evenly populated iterables""" self.assertEqual( list(mi.roundrobin('ABC', [1, 2, 3], range(3))), ['A', 1, 0, 'B', 2, 1, 'C', 3, 2] )
def find_dfas( accepting: list[Word], rejecting: list[Word], solver_fact=Glucose4, sym_mode: SymMode = "bfs", extra_clauses: ExtraClauseGenerator = lambda *_: (), bounds: Bounds = (None, None), order_by_stutter: bool = False, alphabet: frozenset = None, allow_unminimized: bool = False, ) -> Iterable[DFA]: """Finds all minimal dfa that are consistent with the labeled examples. Here "minimal" means that a no DFA with smaller size is consistent with the data. Thus, all returns DFAs are the same size. Inputs: - accepting: A sequence of "words" to be accepted. - rejecting: A sequence of "words" to be rejected. - solver: A py-sat API compatible object for solving CNF SAT queries. - bounds: DFA size range (inclusive) to restrict search to, e.g., - (None, 10): DFA can have as most 10 states. - (2, None): DFA must have at least 2 states. - (2, 10): DFA must have between 2 and 10 states. - (None, None): No constraints (default). - sym_mode: Which symmetry breaking strategy to employ. - extra_clauses: Optional user defined additional clauses to add for a given codec (encoding of size k DFA). - order_by_stutter: Order DFA by number of self loop transitions. - alphabet: Optionally specify the alphabet the DFA should be over. - allow_unminimized: Continue after all minimized (equiv states merges) have been enumerated. Returns: An iterable of all minimal DFA consistent with accepting and rejecting. """ # Convert to hashable words. accepting = list(map(tuple, accepting)) rejecting = list(map(tuple, rejecting)) if set(accepting) & set(rejecting): return elif len(accepting) == len(rejecting) == 0: if not alphabet: raise ValueError('Need examples or an alphabet!') # Conjecture empty string label and interleave dfas. kwargs = { 'solver_fact': solver_fact, 'sym_mode': sym_mode, 'extra_clauses': extra_clauses, 'bounds': bounds, 'order_by_stutter': order_by_stutter, 'alphabet': alphabet, 'allow_unminimized': allow_unminimized, } dfas_pos = find_dfas(accepting=[()], rejecting=[ ], **kwargs) dfas_neg = find_dfas(accepting=[ ], rejecting=[()], **kwargs) yield from roundrobin(dfas_pos, dfas_neg) return apta = APTA.from_examples( accepting=accepting, rejecting=rejecting, alphabet=alphabet ) encodings = dfa_id_encodings( apta=apta, sym_mode=sym_mode, extra_clauses=extra_clauses, bounds=bounds) for codec, clauses in encodings: with solver_fact(bootstrap_with=clauses) as solver: if not solver.solve(): continue if not order_by_stutter: models = solver.enum_models() yield from (extract_dfa(codec, apta, m) for m in models) if allow_unminimized: continue return model = solver.get_model() # Save for analysis below. # Search for maximally stuttering DFAs. models = order_models_by_stutter(solver_fact, codec, clauses, model) yield from (extract_dfa(codec, apta, m) for m in models) if allow_unminimized: continue return
@pyqtSlot(str) def onCurrentTextChanged(self, currentText: str): self.buttonRemove.setEnabled(bool(currentText)) def getTagFiles(self) -> Tuple[List[str], List[str]]: if not (tagPath := self.tagDirLineEdit.text()): return [], [] allowedExt = videoSettings.allowedExtensionsWithDot tagFinder = TagFinder(tagPath) tagNames = [] tagsToGen = {} for i in range(self.listWidget.count()): tagName = self.listWidget.item(i).text() tagNames.append(tagName) if tagName not in tagsToGen: tagsToGen[tagName] = tagFinder.genFilesWithTag( tagName, extensions=allowedExt) genSeq = [tagsToGen[tagName] for tagName in tagNames] tagFiles = [str(path) for path in more_itertools.roundrobin(*genSeq)] return tagFiles, tagNames def genTagGenerators(self) -> Iterable[RowGen]: dirPath = self.tagDirLineEdit.text() for i in range(self.listWidget.count()): tag = self.listWidget.item(i).text() yield RowGen(path=dirPath, tag=tag)
def __iter__(self): return roundrobin(*self.dataloaders)
raise ValueError( f"The fractions must add up to 1; they add up to {total}") if isclose(train, 1.0): return tuple(chain(*((arg, arg[:0], arg[:0]) for arg in args))) train_and_valid = train + valid if isclose(train_and_valid, 1.0): tmp = temporal_train_test_split(*args, train_size=train) all_train, all_valid = tmp[::2], tmp[1::2] return tuple( chain(*((t, v, t[:0]) for t, v in zip(all_train, all_valid)))) tmp = temporal_train_test_split(*args, train_size=train_and_valid) all_train_valid, all_test = tmp[::2], tmp[1::2] tmp = temporal_train_test_split(*all_train_valid, train_size=train / (train + valid)) all_train, all_valid = tmp[::2], tmp[1::2] return tuple(roundrobin(all_train, all_valid, all_test)) @dataclass class TemporalSplit(Generic[T]): X_train: T X_valid: T X_test: T y_train: T y_valid: T y_test: T index_train: Index | None = None index_valid: Index | None = None index_test: Index | None = None @property def shape(self) -> dict[str, tuple[int, ...]]:
def test_even_groups(self): """Ensure ordered output from evenly populated iterables""" self.assertEqual( list(mi.roundrobin("ABC", [1, 2, 3], range(3))), ["A", 1, 0, "B", 2, 1, "C", 3, 2], )