text
stringlengths
81
112k
Return score from B perspective. If W is winning, score is negative. def score(self): 'Return score from B perspective. If W is winning, score is negative.' working_board = np.copy(self.board) while EMPTY in working_board: unassigned_spaces = np.where(working_board == EMPTY) ...
Return supervised examples from positions NOTE: last move is not played because no p.next_move after. def parse_sgf_to_examples(sgf_path): """Return supervised examples from positions NOTE: last move is not played because no p.next_move after. """ return zip(*[(p.position, p.next_move, p.result)...
Finds all sgf files in base_dir with year >= min_year and komi def find_and_filter_sgf_files(base_dir, min_year=None, komi=None): """Finds all sgf files in base_dir with year >= min_year and komi""" sgf_files = [] for dirpath, dirnames, filenames in os.walk(base_dir): for filename in filenames: ...
Returns all model paths in the model_dir. def get_model_paths(model_dir): """Returns all model paths in the model_dir.""" all_models = gfile.Glob(os.path.join(model_dir, '*.meta')) model_filenames = [os.path.basename(m) for m in all_models] model_numbers_names = [ (shipname.detect_model_num(m),...
Turn a game into SGF. Doesn't handle handicap games or positions with incomplete history. Args: move_history: iterable of PlayerMoves result_string: "B+R", "W+0.5", etc. comments: iterable of string/None. Will be zipped with move_history. def make_sgf( move_history, result_str...
A node can either add B+W stones, play as B, or play as W. def handle_node(pos, node): 'A node can either add B+W stones, play as B, or play as W.' props = node.properties black_stones_added = [coords.from_sgf( c) for c in props.get('AB', [])] white_stones_added = [coords.from_sgf( c) f...
Wrapper for sgf files, returning go.PositionWithContext instances. It does NOT return the very final position, as there is no follow up. To get the final position, call pwc.position.play_move(pwc.next_move) on the last PositionWithContext returned. Example usage: with open(filename) as f: ...
Applies the decoder to inputs, given the context from the encoder. :param inputs: tensor with inputs (batch, seq_len) if 'batch_first' else (seq_len, batch) :param context: context from the encoder :param inference: if True inference mode, if False training mode def decode(self, in...
Autoregressive generator, works with SequenceGenerator class. Executes decoder (in inference mode), applies log_softmax and topK for inference with beam search decoding. :param inputs: tensor with inputs to the decoder :param context: context from the encoder :param beam_size: b...
Appends index of the current epoch and index of the current iteration to the name of the file with results. :param epoch: index of the current epoch :param iteration: index of the current iteration def build_eval_path(self, epoch, iteration): """ Appends index of the current ep...
Runs translation on test dataset. :param calc_bleu: if True compares results with reference and computes BLEU score :param epoch: index of the current epoch :param iteration: index of the current iteration :param eval_path: path to the file for saving results :param ...
Runs evaluation on test dataset. :param epoch: index of the current epoch :param iteration: index of the current iteration :param summary: if True prints summary def evaluate(self, epoch, iteration, summary): """ Runs evaluation on test dataset. :param epoch: index of ...
Executes moses detokenizer on eval_path file and saves result to eval_path + ".detok" file. :param eval_path: path to the tokenized input def run_detokenizer(self, eval_path): """ Executes moses detokenizer on eval_path file and saves result to eval_path + ".detok" file. ...
Executes sacrebleu and returns BLEU score. :param detok_eval_path: path to the test file :param reference_path: path to the reference file def run_sacrebleu(self, detok_eval_path, reference_path): """ Executes sacrebleu and returns BLEU score. :param detok_eval_path: path to t...
Configures cloud logging This is called for all main calls. If a $LOGGING_PROJECT is environment variable configured, then STDERR and STDOUT are redirected to cloud logging. def configure(project=LOGGING_PROJECT): """Configures cloud logging This is called for all main calls. If a $LOGGING_PROJEC...
Strategy: suppose that the models that we will create will have prefixes appended to each of its keys, for example due to an extra level of nesting that the original pre-trained weights from ImageNet won't contain. For example, model.state_dict() might return backbone[0].body.res2.conv1.weight, while the pr...
Compute the ratio of gradient norm to weight norm. def compute_update_ratio(weight_tensors, before_weights, after_weights): """Compute the ratio of gradient norm to weight norm.""" deltas = [after - before for after, before in zip(after_weights, before_weights)] delta_norms = [np.linalg.norm(...
Train on examples. def train(*tf_records: "Records to train on"): """Train on examples.""" tf.logging.set_verbosity(tf.logging.INFO) estimator = dual_net.get_estimator() effective_batch_size = FLAGS.train_batch_size if FLAGS.use_tpu: effective_batch_size *= FLAGS.num_tpu_cores if FLAG...
Train on examples and export the updated model weights. def main(argv): """Train on examples and export the updated model weights.""" tf_records = argv[1:] logging.info("Training on %s records: %s to %s", len(tf_records), tf_records[0], tf_records[-1]) with utils.logged_timer("Training...
Freeze a model to a GraphDef proto. def main(unused_argv): """Freeze a model to a GraphDef proto.""" if FLAGS.use_tpu: dual_net.freeze_graph_tpu(FLAGS.model_path) else: dual_net.freeze_graph(FLAGS.model_path)
Itertools recipe >>> list(grouper(3, iter('ABCDEFG'))) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] def grouper(n, iterable): """Itertools recipe >>> list(grouper(3, iter('ABCDEFG'))) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] """ return (iterable[i:i + n] for i in range(0, len(iterable), n))
Sample num_positions postions from each game in sgf_dir Usage: python3 sharp_positions.py subsample --num_positions 10 --sgf_dir data/s NOTE(sethtroisi): see link for a script to truncate SGFs at move number https://github.com/sethtroisi/go-scripts def subsample(): """Sample num_positions...
Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir models/ def evaluate(): """Get Policy and Value for each network, for each position Usage: python3 sharp_positions.py evaluate --sgf_dir data/s --model_dir mode...
Find a subset of problems that maximal explains rating. Usage: python3 sharp_positions.py minimize \ --model_dir models --sgf_dir data/s --rating_json ratings.json --results results.csv def minimize(): """Find a subset of problems that maximal explains rating. Usage: ...
Download content from a url. Args: path: string directory where file will be downloaded url: string url Returns: Full path to downloaded file def download_from_url(path, url): """Download content from a url. Args: path: string directory where file will be downloaded url: string url Re...
Given segmentation masks and the bounding boxes corresponding to the location of the masks in the image, this function crops and resizes the masks in the position defined by the boxes. This prepares the masks for them to be fed to the loss computation as the targets. Arguments: segmentation...
Evaluate detection proposal recall metrics. This function is a much faster alternative to the official COCO API recall evaluation code. However, it produces slightly different results. def evaluate_box_proposals( predictions, dataset, thresholds=None, area="all", limit=None ): """Evaluate detection pro...
Crops the given image to a random part of the image, and randomly flips. We use the fused decode_and_crop op, which performs better than the two ops used separately in series, but note that this requires that the image be passed in as an un-decoded string Tensor. Args: image_buffer: scalar string Tensor r...
Performs central crops of the given image list. Args: image: a 3-D image tensor crop_height: the height of the image following the crop. crop_width: the width of the image following the crop. Returns: 3-D tensor with cropped image. def _central_crop(image, crop_height, crop_width): """Performs ...
Subtracts the given means from each image channel. For example: means = [123.68, 116.779, 103.939] image = _mean_image_subtraction(image, means) Note that the rank of `image` must be known. Args: image: a tensor of size [height, width, C]. means: a C-vector of values to subtract from each chann...
Computes new shape with the smallest side equal to `smallest_side`. Computes new shape with the smallest side equal to `smallest_side` while preserving the original aspect ratio. Args: height: an int32 scalar tensor indicating the current height. width: an int32 scalar tensor indicating the current widt...
Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the resized image. def _aspect_preserving_resize(image, r...
Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized image. Returns: resized_image: A 3-D t...
Preprocesses the given image. Preprocessing includes decoding, cropping, and resizing for both training and eval images. Training preprocessing, however, introduces some random distortion of the image to improve accuracy. Args: image_buffer: scalar string Tensor representing the raw JPEG image buffer. ...
Search for sequence of subtoken ids with the largest probability. Args: symbols_to_logits_fn: A function that takes in ids, index, and cache as arguments. The passed in arguments will have shape: ids -> [batch_size * beam_size, index] index -> [] (scalar) cache -> nested dictionary ...
Return a list of the tensor's shape, and ensure no None values in list. def _shape_list(tensor): """Return a list of the tensor's shape, and ensure no None values in list.""" # Get statically known shape (may contain None's for unknown dimensions) shape = tensor.get_shape().as_list() # Ensure that the shape v...
Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] def _flatten_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] ...
Reshapes first dimension back to [batch_size, beam_size]. Args: tensor: Tensor to reshape of shape [batch_size*beam_size, ...] batch_size: Tensor, original batch size. beam_size: int, original beam size. Returns: Reshaped tensor of shape [batch_size, beam_size, ...] def _unflatten_beam_dim(tensor...
Gather beams from nested structure of tensors. Each tensor in nested represents a batch of beams, where beam refers to a single search state (beam search involves searching through multiple states in parallel). This function is used to gather the top beams, specified by beam_indices, from the nested tensors...
Gather top beams from nested structure. def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
Beam search for sequences with highest scores. def search(self, initial_ids, initial_cache): """Beam search for sequences with highest scores.""" state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, l...
Return initial state dictionary and its shape invariants. Args: initial_ids: initial ids to pass into the symbols_to_logits_fn. int tensor with shape [batch_size, 1] initial_cache: dictionary storing values to be passed into the symbols_to_logits_fn. Returns: state and shap...
Return whether to continue the search loop. The loops should terminate when 1) when decode length has been reached, or 2) when the worst score in the finished sequences is better than the best score in the alive sequences (i.e. the finished sequences are provably unchanging) Args...
Beam search loop body. Grow alive sequences by a single ID. Sequences that have reached the EOS token are marked as finished. The alive and finished sequences with the highest log probabilities and scores are returned. A sequence's finished score is calculating by dividing the log probability by t...
Grow alive sequences by one token, and collect top 2*beam_size sequences. 2*beam_size sequences are collected because some sequences may have reached the EOS token. 2*beam_size ensures that at least beam_size sequences are still alive. Args: state: A dictionary with the current loop state. R...
Gather the top k sequences that are still alive. Args: new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, 2 * beam_size, cur_index + 1] new_log_probs: Log probabilities of new sequences float32 tensor with shape [batch_size, beam...
Combine new and old finished sequences, and gather the top k sequences. Args: state: A dictionary with the current loop state. new_seq: New sequences generated by growing the current alive sequences int32 tensor with shape [batch_size, beam_size, i + 1] new_log_probs: Log probabilities of...
Sets initial random values for trainable parameters. def reset_parameters(self, init_weight): """ Sets initial random values for trainable parameters. """ stdv = 1. / math.sqrt(self.num_units) self.linear_att.data.uniform_(-init_weight, init_weight) if self.normalize: ...
sets self.mask which is applied before softmax ones for inactive context fields, zeros for active context fields :param context_len: b :param context: if batch_first: (b x t_k x n) else: (t_k x b x n) self.mask: (b x t_k) def set_mask(self, context_len, context): """ s...
Calculate Bahdanau score :param att_query: b x t_q x n :param att_keys: b x t_k x n returns: b x t_q x t_k scores def calc_score(self, att_query, att_keys): """ Calculate Bahdanau score :param att_query: b x t_q x n :param att_keys: b x t_k x n return...
Return positional encoding. Calculates the position encoding as a mix of sine and cosine functions with geometrically increasing wavelengths. Defined and formulized in Attention is All You Need, section 3.5. Args: length: Sequence length. hidden_size: Size of the min_timescale: Minimum scale that ...
Calculate bias for decoder that maintains model's autoregressive property. Creates a tensor that masks out locations that correspond to illegal connections, so prediction at position i cannot draw information from future positions. Args: length: int length of sequences in batch. Returns: float tens...
Return float tensor representing the padding values in x. Args: x: int tensor with any shape padding_value: int value that Returns: flaot tensor with same shape as x containing values 0 or 1. 0 -> non-padding, 1 -> padding def get_padding(x, padding_value=0): """Return float tensor representi...
Calculate bias tensor from padding values in tensor. Bias tensor that is added to the pre-softmax multi-headed attention logits, which has shape [batch_size, num_heads, length, length]. The tensor is zero at non-padding locations, and -1e9 (negative infinity) at padding locations. Args: x: int tensor with...
Adds a result to the dictionary. Args: dict_entry: main dict to add entry entry: slot for this entry (likely an integer) dt: the timing for the entry start_time: when the entry started unix time float def _add_result(self, dict_entry, entry, dt, start_time): """Adds a result to the dic...
Sorts dict of results based on log start_time. Sorts the results and returns an array with only the values but sorted by oldest value first.value Args: results_dicts: List of result dicts Returns: List of only the time but sorted oldest first. def _sorted_results(self, results_dicts): ...
Get the compliance level of the output file. def get_compliance(self, filename): """Get the compliance level of the output file.""" print('Running Compliance Check on {}'.format(filename)) print('#' * 80) start_time, status, dt, qual, target = mlp_compliance.l2_check_file_w_starttime( filename)...
Verifies and result and returns timing. Uses submodule mlp_compliance (https://github.com/bitfort/mlp_compliance) Args: log_file: Absolute path to result file. division: open, closed result_name: name of the benchmark, ncf, ssd, etc Returns: Time for the result or `INFINITE_TIME` ...
Compute row block (shard) of expansion for row i of the left_matrix. Compute a shard of the randomized Kronecker product and dump it on the fly. A standard Kronecker product between matrices A and B produces [[a_11 B, ..., a_1n B], ... ...
Compute randomized Kronecker product and dump it on the fly. A standard Kronecker product between matrices A and B produces [[a_11 B, ..., a_1n B], ... [a_m1 B, ..., a_mn B]] (if A's size is (m, n) and B's size is (p, q) then A Kr...
Takes a path to model files and set up a GTP engine instance. def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False, minigui_mode=False): """Takes a path to model files and set up a GTP engine instance.""" n = DualNetwork(load_file) if cgos_mode: player = CGOSPlayer...
Run Minigo in GTP mode. def main(argv): """Run Minigo in GTP mode.""" del argv engine = make_gtp_instance(FLAGS.load_file, cgos_mode=FLAGS.cgos_mode, kgs_mode=FLAGS.kgs_mode, minigui_mode=FLAGS.minigui_mode) db...
Validate a model's performance on a set of holdout data. def validate(*tf_records): """Validate a model's performance on a set of holdout data.""" if FLAGS.use_tpu: def _input_fn(params): return preprocessing.get_tpu_input_tensors( params['batch_size'], tf_records, filter_am...
Validate a model's performance on a set of holdout data. def main(argv): """Validate a model's performance on a set of holdout data.""" _, *validation_paths = argv if FLAGS.expand_validation_dirs: tf_records = [] with utils.logged_timer("Building lists of holdout files"): for re...
Load custom environment setup from a Python source file and run the setup function. def setup_custom_environment(custom_module_path): """Load custom environment setup from a Python source file and run the setup function. """ module = import_file("maskrcnn_benchmark.utils.env.custom_module", custom_...
Finds all models, returning a list of model number and names sorted increasing. Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc] def get_models(): """Finds all models, returning a list of model number and names sorted increasing. Returns: [(13, 000013-modelname), (17, 000017-mode...
Gets the directories under selfplay_dir that match YYYY-MM-DD-HH. def get_hour_dirs(root=None): """Gets the directories under selfplay_dir that match YYYY-MM-DD-HH.""" root = root or selfplay_dir() return list(filter(lambda s: re.match(r"\d{4}-\d{2}-\d{2}-\d{2}", s), gfile.ListDirect...
Prints statistics for the most recent n_back models def game_counts(n_back=20): """Prints statistics for the most recent n_back models""" for _, model_name in get_models[-n_back:]: games = get_games(model_name) print("Model: {}, Games: {}".format(model_name, len(games)))
Performs non-maximum suppression on a boxlist, with scores specified in a boxlist field via score_field. Arguments: boxlist(BoxList) nms_thresh (float) max_proposals (int): if > 0, then only the top max_proposals are kept after non-maximum suppression score_field (st...
Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) def remove_small_boxes(boxlist, min_size): """ Only keep boxes with both sides >= min_size Arguments: boxlist (Boxlist) min_size (int) """ # TODO maybe add an API for queryi...
Compute the intersection over union of two set of boxes. The box order must be (xmin, ymin, xmax, ymax). Arguments: box1: (BoxList) bounding boxes, sized [N,4]. box2: (BoxList) bounding boxes, sized [M,4]. Returns: (tensor) iou, sized [N,M]. Reference: https://github.com/chain...
Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) def cat_boxlist(bboxes): """ Concatenates a list of BoxList (having the same image size) into a single BoxList Arguments: bboxes (list[BoxList]) """ asse...
Generate Location Vectors def _loc_vec(self, loc): """ Generate Location Vectors """ gxy = self.scale_xy*(loc[:, :2, :] - self.dboxes[:, :2, :])/self.dboxes[:, 2:, ] gwh = self.scale_wh*(loc[:, 2:, :]/self.dboxes[:, 2:, :]).log() return torch.cat((gxy, gwh), dim=1)....
ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted location and labels gloc, glabel: Nx4x8732, Nx8732 ground truth location and labels def forward(self, ploc, plabel, gloc, glabel): """ ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted l...
Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src parameters def set_grads(params, params_with_grad): """ Copies gradients from param_with_grad to params :param params: dst parameters :param params_with_grad: src...
Copies parameters from new_params to params :param params: dst parameters :param new_params: src parameters def set_weights(params, new_params): """ Copies parameters from new_params to params :param params: dst parameters :param new_params: src parameters """ ...
Initializes internal state and build fp32 master copy of weights. :param model: fp16 model def initialize_model(self, model): """ Initializes internal state and build fp32 master copy of weights. :param model: fp16 model """ logging.info('Initializing fp32 clone weight...
Performs one step of the optimizer. Applies loss scaling, computes gradients in fp16, converts gradients to fp32, inverts scaling and applies optional gradient norm clipping. If gradients are finite, it applies update to fp32 master weights and copies updated parameters to fp16 model for...
Performs one step of the optimizer. :param loss: value of loss function :param optimizer: optimizer :param update: if True executes weight update def step(self, loss, optimizer, scheduler, update=True): """ Performs one step of the optimizer. :param loss: value of loss...
Return inputs and targets Tensors from a serialized tf.Example. def _parse_example(serialized_example): """Return inputs and targets Tensors from a serialized tf.Example.""" data_fields = { "inputs": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.int64) } parsed = tf.parse_single_exampl...
Indicates whether the example's length is lower than the maximum length. def _filter_max_length(example, max_length=256): """Indicates whether the example's length is lower than the maximum length.""" return tf.logical_and(tf.size(example[0]) <= max_length, tf.size(example[1]) <= max_length...
Returns the maximum length between the example inputs and targets. def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0]) return length
Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_max = [4, 8, 16, 24, 25] Args: max_length: The maximum length of example in dataset. min_boundary: Minimu...
Group examples by similar lengths, and return batched dataset. Each batch of similar-length examples are padded to the same length, and may have different number of elements in each batch, such that: group_batch_size * padded_length <= batch_size. This decreases the number of padding tokens per batch, which...
Create dataset where each item is a dict of "inputs" and "targets". Args: file_pattern: String used to match the input TFRecord files. batch_size: Maximum number of tokens per batch of examples max_length: Maximum number of tokens per example num_cpu_cores: Number of cpu cores for parallel input proc...
Load and return dataset of batched examples for use during training. def train_input_fn(params): """Load and return dataset of batched examples for use during training.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-train*") return _read_and_batch_from_files( file_pattern, params...
Load and return dataset of batched examples for use during evaluation. def eval_input_fn(params): """Load and return dataset of batched examples for use during evaluation.""" file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-dev*") return _read_and_batch_from_files( file_pattern, param...
Reduce the loss dictionary from all processes so that process with rank 0 has the averaged results. Returns a dict with the same fields as loss_dict, after reduction. def reduce_loss_dict(loss_dict): """ Reduce the loss dictionary from all processes so that process with rank 0 has the averaged resu...
Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: namespace object returned by arg parser. Raises: ValueError: If an invalid dtype is provided. def parse_dtype_info(flags): """Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: ...
Calculation of IoU based on two boxes tensor, Reference to https://github.com/kuangliu/pytorch-ssd input: box1 (N, 4) box2 (M, 4) output: IoU (N, M) def calc_iou_tensor(box1, box2): """ Calculation of IoU based on two boxes tensor, Reference to ht...
Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox def scale_back_batch(self, bboxes_in, scores_in): """ Do scale and transform from xywh to ltrb suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox """ if bboxes_in.device == ...
Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors are centered on stride / 2, have (approximate) sqrt areas of the specified sizes, and aspect ratios as given. def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): """Generates a matrix of anch...
Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, ...
Converts from a flattened coordinate to a Minigo coordinate. def from_flat(flat): """Converts from a flattened coordinate to a Minigo coordinate.""" if flat == go.N * go.N: return None return divmod(flat, go.N)
Converts from a Minigo coordinate to a flattened coordinate. def to_flat(coord): """Converts from a Minigo coordinate to a flattened coordinate.""" if coord is None: return go.N * go.N return go.N * coord[0] + coord[1]
Converts from an SGF coordinate to a Minigo coordinate. def from_sgf(sgfc): """Converts from an SGF coordinate to a Minigo coordinate.""" if sgfc is None or sgfc == '' or (go.N <= 19 and sgfc == 'tt'): return None return _SGF_COLUMNS.index(sgfc[1]), _SGF_COLUMNS.index(sgfc[0])
Converts from a GTP coordinate to a Minigo coordinate. def from_gtp(gtpc): """Converts from a GTP coordinate to a Minigo coordinate.""" gtpc = gtpc.upper() if gtpc == 'PASS': return None col = _GTP_COLUMNS.index(gtpc[0]) row_from_bottom = int(gtpc[1:]) return go.N - row_from_bottom, col
Converts from a Minigo coordinate to a GTP coordinate. def to_gtp(coord): """Converts from a Minigo coordinate to a GTP coordinate.""" if coord is None: return 'pass' y, x = coord return '{}{}'.format(_GTP_COLUMNS[x], go.N - y)
Wraps cv2.findContours to maintain compatiblity between versions 3 and 4 Returns: contours, hierarchy def findContours(*args, **kwargs): """ Wraps cv2.findContours to maintain compatiblity between versions 3 and 4 Returns: contours, hierarchy """ if cv2.__version__.sta...
Adds child node for fcoord if it doesn't already exist, and returns it. def maybe_add_child(self, fcoord): """ Adds child node for fcoord if it doesn't already exist, and returns it. """ if fcoord not in self.children: new_position = self.position.play_move( coords.from_flat...