def forward_kinematics(self, hip_angle, knee_angle): hip_global_angle = hip_angle - np.pi knee_global_angle = knee_angle - np.pi / 2 knee_rod_s = self.knee_base knee_rod_e = knee_rod_s + self.knee_rod * rotated(knee_global_angle) hip_s = self.hip_base hip_e = hip_s + self.hip * rotated(hip_global_angle) knee, shin_angle = find_left_triangle(self.knee_connection_rod, self.knee_offset, knee_rod_e, hip_e, get_b_global_angle=True) if self.invalide_state(shin_angle, knee): return None foot = knee - self.shin * rotated(shin_angle) return HindLegState(hip_s=hip_s, hip_e=hip_e, knee_rod_s=knee_rod_s, knee_rod_e=knee_rod_e, foot=foot, knee=knee, hip_angle=hip_angle, knee_angle=knee_angle, shin_angle=shin_angle)
def gen_batch(_): inputs, outputs, dist_outputs = [], [], [] for _ in range(self.hps.batch_size): im, (x, y) = self.sample_im_xy(train_images, square_validation) if random.random() < self.hps.oversample: for _ in range(1000): if im.mask[x:x + s, y:y + s].sum(): break im, (x, y) = self.sample_im_xy(train_images, square_validation) patch = im.data[:, x - mb:x + s + mb, y - mb:y + s + mb] mask = im.mask[:, x - m:x + s + m, y - m:y + s + m] if self.hps.needs_dist: dist_mask = im.dist_mask[:, x - m:x + s + m, y - m:y + s + m] if self.hps.augment_flips: if random.random() < 0.5: patch = np.flip(patch, 1) mask = np.flip(mask, 1) if self.hps.needs_dist: dist_mask = np.flip(dist_mask, 1) if random.random() < 0.5: patch = np.flip(patch, 2) mask = np.flip(mask, 2) if self.hps.needs_dist: dist_mask = np.flip(dist_mask, 2) if self.hps.augment_rotations: assert self.hps.augment_rotations != 1 # old format angle = (2 * random.random() - 1.) * self.hps.augment_rotations patch = utils.rotated(patch, angle) mask = utils.rotated(mask, angle) if self.hps.needs_dist: dist_mask = utils.rotated(dist_mask, angle) if self.hps.augment_channels: ch_shift = np.random.normal(1, self.hps.augment_channels, patch.shape[0]) patch = patch * ch_shift[:, None, None] inputs.append(patch[:, m:-m, m:-m].astype(np.float32)) outputs.append(mask[:, m:-m, m:-m].astype(np.float32)) if self.hps.needs_dist: dist_outputs.append(dist_mask[:, m:-m, m:-m].astype(np.float32)) return (torch.from_numpy(np.array(inputs)), torch.from_numpy(np.array(outputs)), torch.from_numpy(np.array(dist_outputs)))
def get_patch_target(self): item = None skipped = {4} # pups - too small, not confused while item is None or item.name not in self.imgs or item.cls in skipped: item = self.coords.iloc[random.randint(0, len(self.coords) - 1)] img_id = item.name img = self.imgs[img_id] max_y, max_x = img.shape[:2] s = self.patch_size scale_aug = not (self.min_scale == self.max_scale == 1) if scale_aug: scale = random.uniform(self.min_scale, self.max_scale) s = int(np.round(s / scale)) b = int(np.ceil(np.sqrt(2) * s / 2)) x0, y0 = item.col, item.row off = self.offset half = int(round(2 * b + s) / 2) try: x = random.randint(max(x0 - off, half), min(x0 + off, max_x - half)) y = random.randint(max(y0 - off, half), min(y0 + off, max_y - half)) except ValueError: return None patch = img[y - half:y + half, x - half:x + half] angle = random.random() * 360 patch = utils.rotated(patch, angle) patch = patch[b:, b:][:s, :s] if (patch == 0).sum() / s**2 > 0.02: return None # masked too much if scale_aug: patch = cv2.resize(patch, (self.patch_size, self.patch_size)) assert patch.shape == (self.patch_size, self.patch_size, 3), patch.shape return self.transform(patch), int(item.cls)
def orientations(tile): """Generates all 8 orientations of a 2D array.""" for _ in range(2): for _ in range(4): yield tile tile = rotated(tile) tile = transposed(tile)
def isCircular( n ): digits = int( log10( n ) ) for _ in xrange( digits + 1 ): if not isPrime( n ): return False # rotate the number n = rotated( n, digits ) return True
def gen_batch(xy_batch_): inputs_ = [] for x, y in xy_batch_: # shifted by -b to account for padding patch = padded[:, x:x + s + 2 * b, y:y + s + 2 * b] inputs_.append(patch) for i in range(1, n_rot): inputs_.append(utils.rotated(patch, i * 90)) return xy_batch_, np.array(inputs_, dtype=np.float32)
def predict_image_mask(self, im_data: np.ndarray, rotate: bool = False, no_edges: bool = False, average_shifts: bool = True) -> np.ndarray: self.net.eval() c, w, h = im_data.shape b = self.hps.patch_border s = self.hps.patch_inner padded = np.zeros([c, w + 2 * b, h + 2 * b], dtype=im_data.dtype) padded[:, b:-b, b:-b] = im_data # mirror on the edges padded[:, :b, b:-b] = np.flip(im_data[:, :b, :], 1) padded[:, -b:, b:-b] = np.flip(im_data[:, -b:, :], 1) padded[:, :, :b] = np.flip(padded[:, :, b:2 * b], 2) padded[:, :, -b:] = np.flip(padded[:, :, -2 * b:-b], 2) step = s // 3 if average_shifts else s margin = b if no_edges else 0 xs = list(range(margin, w - s - margin, step)) + [w - s - margin] ys = list(range(margin, h - s - margin, step)) + [h - s - margin] all_xy = [(x, y) for x in xs for y in ys] out_shape = [self.hps.n_classes, w, h] pred_mask = np.zeros(out_shape, dtype=np.float32) pred_per_pixel = np.zeros(out_shape, dtype=np.int16) n_rot = 4 if rotate else 1 def gen_batch(xy_batch_): inputs_ = [] for x, y in xy_batch_: # shifted by -b to account for padding patch = padded[:, x:x + s + 2 * b, y:y + s + 2 * b] inputs_.append(patch) for i in range(1, n_rot): inputs_.append(utils.rotated(patch, i * 90)) return xy_batch_, np.array(inputs_, dtype=np.float32) for xy_batch, inputs in utils.imap_fixed_output_buffer( gen_batch, tqdm.tqdm( list( utils.chunks(all_xy, self.hps.batch_size // (4 * n_rot)))), threads=2): y_pred = self.net(self._var(torch.from_numpy(inputs))) for idx, mask in enumerate(y_pred.data.cpu().numpy()): x, y = xy_batch[idx // n_rot] i = idx % n_rot if i: mask = utils.rotated(mask, -i * 90) # mask = (mask >= 0.5) + 0.001 pred_mask[:, x:x + s, y:y + s] += mask / n_rot pred_per_pixel[:, x:x + s, y:y + s] += 1 if not no_edges: assert pred_per_pixel.min() >= 1 pred_mask /= np.maximum(pred_per_pixel, 1) return pred_mask
def find_left_triangle(a, b, c_s, c_e, get_b_global_angle=False): c_vec = (c_e - c_s) * vec(1, -1) c = np.linalg.norm(c_vec) if c == 0: c = np.nan d = (c**2 + b**2 - a**2) / (2 * c) b_global_angle = np.pi - (get_angle(c_vec) + np.arccos(d / b)) vertex = c_e + b * rotated(b_global_angle) return (vertex, b_global_angle) if get_b_global_angle else vertex
# Read problem input for line in fileinput.input(): if line.startswith('Tile'): id = int(line.replace(':', '').split(' ')[1]) elif len(line) > 5: TILES[id].append(line.strip()) # Map edges to pieces that share that edge piece_edges = defaultdict(set) for id, tile in TILES.items(): for _ in range(4): row = ''.join(tile[0]) piece_edges[row].add(id) piece_edges[row[::-1]].add(id) tile = rotated(tile) # Construct graph of neighbouring pieces graph = defaultdict(set) for neighbouring_pieces in piece_edges.values(): for x, y in permutations(neighbouring_pieces, 2): graph[x].add(y) # Corners are the only pieces that neighbour exactly 2 other tiles. corners = [tile for tile, neighs in graph.items() if len(neighs) == 2] print "Corner ID product:", mul(corners) print # Build up the full arrangement of the tiles. Arbitrarily pick # a corner to be the top-left, and assign its neighbours.
tiles[curr] = copy.deepcopy(board) edges = Counter() piece_edges = defaultdict(set) # find edges: for id, t in tiles.items(): x = copy.deepcopy(t) for _ in range(4): row = ''.join(x[0]) edges[row] += 1 edges[row[::-1]] += 1 piece_edges[row].add(id) piece_edges[row[::-1]].add(id) x = rotated(x) # for c in edges.most_common(): # print c cands = [] for id, tile in tiles.items(): ones = 0 for _ in range(4): row = ''.join(x[0]) if edges.get(row) == 1: ones += 1 if edges.get(row[::-1]) == 1: ones += 1 x = rotated(x)